【问题标题】:Conditional in print statement doesn't print the rest of it. Javaprint 语句中的条件不会打印其余部分。爪哇
【发布时间】:2015-06-26 09:35:06
【问题描述】:

所以这里有一个简单的代码来调整正确的“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!

问题是“数字”在哪里!用“1st”的情况??

【问题讨论】:

  • 好的,谢谢大家,我明白了。我认为放置("st"):(i==2? "nd":i==3? "rd":"th") 而不是"st":i==2? "nd":i==3? "rd":"th" 会限制条件的边界。但显然它不是那样工作的..所以把整个条件放在括号里就可以了。谢谢大家:)

标签: java printing conditional-statements


【解决方案1】:

你忘记带牙套了,换一个:

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!");
                    ^                                         ^

【讨论】:

    【解决方案2】:

    注意您的打印状况:

    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.
    

    【讨论】:

      【解决方案3】:
      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!");
      

      【讨论】:

      • 我认为这不是 OP 打算这样做的方式 - 它应该也可以工作!
      猜你喜欢
      • 2012-08-15
      • 1970-01-01
      • 1970-01-01
      • 2021-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-11
      • 2022-08-21
      相关资源
      最近更新 更多