我试图编写一些代码,让用户输入有效的用户名,他们会尝试三次尝试。每当我编译它时,只要我有一个else if语句,我就会得到一个 else without 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;
}
答案 0 :(得分:9)
您误解了if-else
if(condition){
//condition is true here
}else{
//otherwise
}else if{
// error cause it could never be reach this condition
}
了解更多The if-then and if-then-else Statements
你可以拥有
if(condition){
}else if (anotherCondition){
}else{
//otherwise means 'condition' is false and 'anotherCondition' is false too
}
答案 1 :(得分:3)
如果您有if
后跟else
,则结束该块。您可以if
后跟多个else if
语句,但只有一个else
- else
必须是最后一个。
答案 2 :(得分:0)
您需要:将除“last else”之外的所有“else”更改为“else if”,或者在以下“else if”语句之前添加“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");
}
答案 3 :(得分: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
}
}