打印语句中的条件不打印其余部分。 Java
Conditional in print statement doesn't print the rest of it. Java
所以这里有一个简单的代码来调整右边的"st"、"nd"、"rd"、"th"与输入的数字。 出于某种原因将其置于循环中。没关系。
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!
问题是 "number!" 的情况是“1st”?
注意打印的情况:
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.
您忘记带一对牙套,更改:
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!");
^ ^
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!");
所以这里有一个简单的代码来调整右边的"st"、"nd"、"rd"、"th"与输入的数字。 出于某种原因将其置于循环中。没关系。
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!
问题是 "number!" 的情况是“1st”?
注意打印的情况:
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.
您忘记带一对牙套,更改:
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!");
^ ^
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!");