2015-04-19 102 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