2

I want to display multiples of 5 from 0 to 30 but not using normal logic. Tried with Ternary operator to display the result.

     int i=0;
     while(++i<=30)
     System.out.print(i%5==0?i:" ");

Output

      5    10    15    20    25   

I don't want any spaces to be printed so instead on " " in the above code I tried with continue statement to proceed with the loop but it did not worked.

 System.out.print(i%5==0?i:continue);

This code throws invalid expression. Why apart from expression special instructions did not work. Please help me in giving expression that do nothing in the ternary operator.

Razib
  • 10,965
  • 11
  • 53
  • 80
Mohan Raj
  • 1,104
  • 9
  • 17
  • did you try an empty string? `System.out.print(i%5==0?i:"");` – TobiasR. May 05 '15 at 07:54
  • 1
    I marked this as a duplicate, since too many believe that the `ternary` operator is just another way of writing an `if-else` statement. That's not true and you shouldn't attempt to shoehorn it everywhere. Read the accepted answer for the duplicate to learn the full truth about the ternary operator. – Kayaman May 05 '15 at 08:08

6 Answers6

1

Ternary operator expects (in this case) an string, so to achieve your needs you must print an empty String if condition is false:

 System.out.print(i%5==0?i:"");
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
1

Just use an empty string

System.out.print(i%5==0?i:"");
TobiasR.
  • 826
  • 9
  • 19
0

Because System.out.print(continue) is not valid. Check java tutorials on how conditional operator works.

Ternary operator can be thought of as a conditional assignment. In your case, with continue you are not assigning anything (to the parameter of System.out.print())

You can simply use "" instead of " " and you would get the expected output

kaykay
  • 556
  • 2
  • 7
0

You can't return a keyword! Even if this did work, you would still be passing it into System.out.print so would you expect a space/0-length string to be printed?

This is the equivalent:

System.out.print(i%5 == 0 ? "" + i : "");
Steve Chaloner
  • 8,162
  • 1
  • 22
  • 38
0

The problem with System.out.println(). Since System.out.println() always expect something that can be print eg.- String, int, byte etc.

But here continue is a statement to manage the control flow of a program and in returns nothing.

In this context you don't need to add the continue statement, since the flow is automatically do what you expect. And since you want to avoid space then you can do this -

int i=0;
while(++i<=30)
   System.out.print(i%5==0?i : "");
Razib
  • 10,965
  • 11
  • 53
  • 80
-1

You need an argument to the println() method, not a directive.

But I think it's cleaner to use an "if" instead: if (i%5 == 0) System.out.println("" + i);

Ronald
  • 2,842
  • 16
  • 16