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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With