use*_*515 4 java if-statement conditional-statements
我正在尝试编写一些代码,使用户输入有效的用户名,他们会尝试三次.每次我编译它时,如果我有一个else if语句,我得到一个没有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;
}
Run Code Online (Sandbox Code Playgroud)
你误解了使用 if-else
if(condition){
//condition is true here
}else{
//otherwise
}else if{
// error cause it could never be reach this condition
}
Run Code Online (Sandbox Code Playgroud)
你可以有
if(condition){
}else if (anotherCondition){
}else{
//otherwise means 'condition' is false and 'anotherCondition' is false too
}
Run Code Online (Sandbox Code Playgroud)