简体   繁体   中英

Conditional in print statement doesn't print the rest of it. Java

So here's a simple code to adjust the right "st", "nd", "rd", "th" with the input number. It's placed in a loop for a reason. Nevermind that.

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

when num is input as 5 here's the output:

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

Question is where's "number!" with the case "1st"??

Notice the condition of your print :

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

I added parenthesis to the false part so it is easier for you to understand.

I believe what you want is :

(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.

You forgot a pair of braces, change:

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

to:

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

is the source of the problem. Do you see how you have + " number!"); after the : that separates the 1st and the 2nd/3rd? You need to have this twice.

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

or

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM