2014-02-20 41 views
4

我想寫一些代碼,使用戶輸入一個有效的用戶名,他們得到三個嘗試去做。每次我編譯它時,我都會得到一個else if 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; 
    } 
+0

'如果(條件){}其他{}否則{}'看起來不正確。首先'else'處理情況是錯誤的情況,但是第二個'else'應該處理的情況是什麼? – Pshemo

回答

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 
} 
3

如果你有一個if後跟else重圓該塊。您可以有if後跟多個else if語句,但只有一個else - 和else必須是最後一個。

+0

你會怎麼說一個字符串不等於另一個字符串 – user3285515

+0

聽起來像你想要「不」操作符:!例如,'if(!string1.equals(string2)){...}' –

0

您需要:改變所有的「其他」除「如果別人」最後「否則,如果」,或者把簡單的「如果」之前,下面的語句:

(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 
     } 
    } 
相關問題