2017-02-19 35 views
1
import java.util.Scanner; 
import static java.lang.System.*; 

public class Whativelearned { 

    enum MyfirstEnum {one, two, three} 

    public static void main(String[] args) { 
     Scanner keyboardinput = new Scanner(in); 
     MyfirstEnum trolley; 
     char a1; 

     out.println("Do you pee in the shower"? Y/N"); 
     a1 = keyboardinput.findWithinHorizon(".", 0).charAt(0); 


     if (a1=='Y'||a1=='y') { 
      trolley=MyfirstEnum.one; 
      out.println("Ewwwwwww"); 
     } 


     if (a1=='N'||a1=='n') { 
      trolley=MyfirstEnum.two; 
      out.println("Well somebody isn't being very honest"); 
     }else { 
      out.println("You're not so keen on following instructions, are you?"); 
     } 

     keyboardinput.close(); 
    } 

} 

我希望我的else語句覆蓋所有的結果,除了在if案件的案件。
正如我希望它作爲(!(a1=='Y'||(a1=='y'||a1=='n'||a2=='N'))我else語句似乎並沒有發揮作用(JAVA)

但是當我運行它的上市else聲明似乎在所有情況下被執行。

+3

你else語句是指最後'if'塊只有這樣,它只被觸發時'(!(A1 == 'N' || A2 == 'N'))'。 –

回答

1

試試這個

if (a1=='Y' || a1=='y') { 
    trolley=MyfirstEnum.one; 
    out.println("Ewwwwwww"); 
} else if (a1=='N' || a1=='n') { 
    trolley = MyfirstEnum.two; 
    out.println("Well somebody isn't being very honest"); 
} else { 
    out.println("You're not so keen on following instructions, are you?"); 
} 
+0

與switch語句甚至更好: ' 開關(A1){ 情況下( 'Y'): 情況下( 'Y'):{ 手推車= MyfirstEnum.one; out.println(「Ewwwwwww」); 休息; } case('N'): case('n'):{ trolley = MyfirstEnum.two; (「嗯,有人不是很誠實」); 休息; } 默認:{ out.println(「你不那麼熱衷於遵循指示,是嗎?「); } } ' –

0

else語句總是具體到一個if聲明。因此,只要最後的if條件未得到滿足,就會執行您的else子句。

無法比擬的條件都滿足時,只執行你的條款,你需要改變你的if語句else if像這樣:

if (a1 == 'y' || a1 == 'Y') { 
    // ... 
} else if (a1 == 'n' || 'a1 == 'N') { 
    // ... 
} else { 
    // .... 
} 

另一種方式來解決這將是使用switch聲明。這些用於比較變量和一組常量。您可以使用它們像這樣:

switch (a1) { 
    case 'y': 
    case 'Y': 
     // ... 
     break; 
    case 'n': 
    case 'N': 
     // ... 
     break; 
    default: 
     // ... 
} 

請閱讀一些更多關於switch聲明你嘗試在其他情況之前。

0

只要寫else befor第二for循環:

else if (a1=='N'||a1=='n') { 
0

代碼執行是最好的預演理解。

  1. 如果你在你的代碼中做了,你會發現第一個if語句被檢查,如果它的值爲true,那麼它的相應的進程被執行。
  2. 現在控件向下移動以執行下一個if語句。此if聲明檢查與上述if互斥的條件。如果其爲真(僅在上述情況爲假時),則執行其相應的過程,如果其爲假,則執行零件過程。

您需要使用之後if elseif其次是else