【问题标题】:I keep getting an "else without if" error我不断收到“else without if”错误
【发布时间】:2014-03-22 00:19:04
【问题描述】:

我正在尝试编写一些代码,让用户输入一个有效的用户名,并且他们尝试了三次。每次我编译它时,我都会得到一个 else without if 错误,只要我有 else if 语句。

  Scanner in = new Scanner(System.in);

  String validName = "thomsondw";

  System.out.print("Please enter a valid username: ");
  String input1 = in.next();

  if (input1.equals(validName))
  {
    System.out.println("Ok you made it through username check");
  }
  else
  {
    String input2 = in.next(); 
  }
  else if (input2.equals(validName))
  {
    System.out.println("Ok you made it through username check");
  }
  else
  {
    String input3 = in.next();
  }
  else if (input3.equals(validName))
  {
    System.out.println("Ok you made it through username check");
  }
  else
  {
    return;
  }

【问题讨论】:

  • if(condition){ }else{ }else{ } 似乎不对。第一个else 处理条件为假的情况,但第二个else 应该处理什么?

标签: java if-statement conditional-statements


【解决方案1】:

你误会if-else的用法

if(condition){
  //condition is true here
}else{
  //otherwise
}else if{
  // error cause it could never be reach this condition
}

阅读更多The if-then and if-then-else Statements

你可以拥有

if(condition){

}else if (anotherCondition){

}else{
  //otherwise means  'condition' is false and 'anotherCondition' is false too
}

【讨论】:

    【解决方案2】:

    如果您有一个 if 后跟一个 else,则该块结束。您可以在if 后面跟多个else if 语句,但只有一个else -- 并且else 必须在最后。

    【讨论】:

    • 如何说一个字符串不等于另一个字符串
    • 听起来你想要“not”运算符:!。例如,if (! string1.equals(string2)) { ... }
    【解决方案3】:

    您需要:将除最后一个之外的所有“else”更改为“else if”,或在以下“else if”语句之前放置简单的“if”:

    (1)

    else if (input2.equals(validName))
    {
        System.out.println("Ok you made it through username check");
    }
    

    (2)

    else if (input3.equals(validName))
    {
        System.out.println("Ok you made it through username check");
    }
    

    【讨论】:

      【解决方案4】:

      您的代码不是很容易维护。如果用户尝试了 5 次,你会怎么做?添加一些额外的 if 块?如果用户有 10 次尝试呢? :-) 你明白我的意思。

      请尝试以下方法:

              Scanner in = new Scanner(System.in);
          int tries = 0;
          int maxTries = 3;
          String validName = "thomsondw"; 
          while (tries < maxTries) {
              tries++;
              System.out.print("Please enter a valid username: ");
              String input = in.next();
              if (input.equals(validName)) {
                  System.out.println("Ok you made it through username check");
                  break; //leaves the while block
              } 
          }
      

      【讨论】:

        猜你喜欢
        • 2022-07-20
        • 2013-02-06
        • 1970-01-01
        • 2023-04-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多