Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
  }
like image 915
user3285515 Avatar asked Dec 16 '22 01:12

user3285515


1 Answers

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
}
like image 52
nachokk Avatar answered Dec 31 '22 19:12

nachokk