I want to print integer in new line.
like
1
2
3
..
how I do that with System.out.println(a,b,c)
// here comma used only for explain this. Can you help me?
System.out.println(a,b,c)
I want to print integer in new line.
like
1
2
3
..
how I do that with System.out.println(a,b,c)
// here comma used only for explain this. Can you help me?
System.out.println(a,b,c)
Here's an example using Java 9+ functionality to do this (do note that it creates an extra List, so don't do this for too many objects):
List.of(a, b, c).forEach(System.out::println);
If you have trouble with the types, then you can do the following:
List.<Object>of(a, b, c).forEach(System.out::println);
In Java 8, you can do the following instead:
Arrays.asList(a, b, c).forEach(System.out::println);
//If this doesn't work, do this:
Arrays.asList(a, b, c).forEach(i -> System.out.println(i));
//If the types don't work, do this:
Arrays.<Object>asList(a, b, c).forEach(System.out::println);
//If none of them work, do this:
Arrays.<Object>asList(a, b, c).forEach(i -> System.out.println(i));
Here's an example using String.format, which doesn't create any extra lists:
System.out.println(String.format("%d\n%d\n%d\n", a, b, c));
You can improve this by directly using System.out.format, like so:
System.out.format("%d\n%d\n%d\n", a, b, c);
You either use 3 calls to println(int x)
:
System.out.println(a);
System.out.println(b);
System.out.println(c);
Or a single call to println(String x)
, using lineSeparator()
and string concatenation:
System.out.println(a + System.lineSeparator() + b + System.lineSeparator() + c);
Or a single call to printf
: (I recommended this one)
System.out.printf("%d%n%d%n%d%n", a, b, c);
You can create a method using vargars:
public static void printIntegers(int... ints){
for(int i: ints) System.out.println(i);
}
And use that method to print all integers you need:
printIntegers(1,2,3,4);
if you wanna print in a sequence from x-y then you can use this method A)
for(int i=x;i<=y;i++)
{ System.out.println(i);
}
or if you want to print three nums like 1 ,2 and 3 then:
System.out.println(1);
System.out.println(2);
System.out.println(3);