Home > OS >  How do I print these variables in the same line (JAVA)?
How do I print these variables in the same line (JAVA)?

Time:09-30

I'm stuck on printing these variables in the same line in Java, I'm new and used to python, couldn't find help online could someone help?

    public static void main (String[] args) {
        byte age = 30;
        float price = 10.99F;
        long viewCount = 1_123_456_789L;
        char initial = 'J';
        System.out.println(age, price, viewCount, initial);
    }
}

CodePudding user response:

the method System.out.println add a new line. if u want print all in the same line you can use System.out.print(age " " price " " viewCount " " initial);

CodePudding user response:

Next to the println-Method (for: print line), there is also a print method. The difference is, well, println always prints out a new line when executed.

Both expect a String as a parameter. So there are multiple ways to solve it, you can either call print for every variable or - what I would recommend - build a String:

System.out.println(age   " "   price   " "   viewCount   " "   initial);

CodePudding user response:

There are different ways.

  • If you need to log application runtime values in a file for future troubleshooting purposes, you will use a logging framework and the most common practice will be log.info("Value: {}", value); where log is a Logger object (Slf4j or other API).
  • If you just want to use System.out, you could:
    • Use System.out.printf("%s, %s\n", v1, v2)
    • Concat all the variables using (less readable) and use System.out.println
    • Use String.format or MessageFormat to get the formatted log message first and then print it with System.out.println

In your case, I'd recommend using the printf approach. You could use:

System.out.printf("%s, %s, %s, %s\n", age, price, viewCount, initial);

This will print:

30, 10.99, 1123456789, J

Other approaches:

System.out.println(String.format("%s, %s, %s, %s", age, price, viewCount, initial));
System.out.println(MessageFormat.format("{0}, {1}, {2}, {3}", age, price, viewCount, initial));

Console output:

30, 10.99, 1123456789, J
30, 10.99, 1,123,456,789, J

  • Related