2015-04-19 103 views
1

所以這裏有一個簡單的代碼,用輸入的數字來調整正確的「st」,「nd」,「rd」,「th」。 由於某種原因,它被放置在一個循環中。不要管那個。有條件的打印語句不打印其餘部分。 Java

System.out.println("How many?"); 
int num = x.nextInt(); 
for(int i=1;i<=num;i++){ 
    System.out.print("Enter the " + i); 
    System.out.println(i==1? ("st"):(i==2? "nd":i==3? "rd":"th") + " number!"); 
} 

當num是輸入作爲5這裏的輸出: 「數」

Enter the 1st 
Enter the 2nd number! 
Enter the 3rd number! 
Enter the 4th number! 
Enter the 5th number! 

的問題是在哪裏與案例「第一」?

+0

好感謝大家,我得到它。我認爲把「(」st「):(i == 2?」nd「:i == 3?」rd「:」th「)'而不是'」st「:i == 2? 「ND」:我== 3? 「rd」:「th」會限制條件的邊界。但顯然它不這樣工作......所以把整個條件放在括號內就可以了。謝謝大家:) –

回答

3

你忘了一對大括號,變化:

System.out.println(i==1? ("st"):(i==2? "nd":i==3? "rd":"th") + " number!"); 

到:

System.out.println((i==1? ("st"):(i==2? "nd":i==3? "rd":"th")) + " number!"); 
        ^          ^
3

通知打印出的條件:

i == 1 ? ("st") : ((i==2? "nd":i==3? "rd":"th") + " number!") 
     ^       ^
     true       false 

我加括號的虛假部分,因此它是您更容易理解。

我相信你想要的是:

(i == 1 ? ("st") : (i==2? "nd":i==3? "rd":"th")) + " number!" 
                ^
       Now we add it to the result of what is returned for the condition. 
2
System.out.println(i==1? ("st"):(i==2? "nd":i==3? "rd":"th") + " number!"); 

是源問題。你看到你有多少+「號碼!」);之後:分開第一和第二/第三?你需要有兩次。

System.out.println(i==1? ("st number"):(i==2? "nd":i==3? "rd":"th") + " number!"); 

System.out.println((i==1? ("st"):(i==2? "nd":i==3? "rd":"th")) + " number!"); 
+0

以爲我不認爲這就是OP如何打算這麼做的 - 它應該也能工作! – alfasin