PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, August 18, 2022

[FIXED] How to print multiple integers on new lines in Java

 August 18, 2022     java, output, text-formatting     No comments   

Issue

I am figuring how to print the results of 4 integers on separate lines by typing only one System.out.println (I guess typing less is better for coders).

Expected Output :

43 
1 
19 
13

My code:

class JavaApplication1 {
     public static void main(String[] args) {
         int a,b,c,d;
         a = -5 + 8 * 6;
         b = (55+9) % 9;
         c = 20 + -3*5 / 8;
         d = 5 + 15 / 3 * 2 - 8 % 3 ;

         System.out.println(a);
         System.out.println(b);
         System.out.println(c);
         System.out.println(d);
    }  
}

Solution

You can do i with several ways :

This will print the variable and between each a new-line char :

System.out.println(a + "\n" + b + "\n" + c + "\n" + d);

You can also use method reference and Arrays, this will create a dynamic List from the array composed of your 4 variables, and apply System.out::println to each one :

Arrays.asList(a,b,c,d).forEach(System.out::println);

or

IntStream.of(a,b,c,d).forEach(System.out::println);

Use a basic for each loop can also be a way :

for (int i : new int[]{a, b, c, d})
     System.out.println(i);

Print with format also :

System.out.printf("%d%n%d%n%d%n%d%n",a,b,c,d)


Answered By - azro
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing