I keep getting the error "else without if"

I try to write code that forces the user to enter the correct username, and they get three attempts to do this. Every time I compile it, I get else with no error wherever I have an 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;
  }
+4
source share
4 answers

You do not understand the use if-else

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

More info If-then and if-then-else statements

You may have

if(condition){

}else if (anotherCondition){

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

if, else, . if, else if, else - else .

+3

: "else", , "else if", "if" "else 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");
}
0

. , 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
        } 
    }
0

Source: https://habr.com/ru/post/1527981/


All Articles