简体   繁体   中英

I keep getting an “else without if” error

I'm trying to write some code that makes the user input a valid username and they get three tries to do it. Every time I compile it I get an else without if error wherever I have a else if statement.

  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;
  }

You are misunderstanding the use of if-else

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

Read more The if-then and if-then-else Statements

You can have

if(condition){

}else if (anotherCondition){

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

If you have an if followed by an else , that ends the block. You can have if followed by multiple else if statements, but only one else -- and the else must be last.

You need to either: change all your "else" except the last to "else if", or put plain "if" before the following "else if" statements:

(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");
}

Your code is not very maintainable. What would you do, if the user got 5 tries? Add some additional if blocks? And what if the user has 10 tries? :-) You see what I mean.

Try the following instead:

        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
        } 
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM