Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Making System.out.println() argument span multiple lines?

Tags:

java

I have the following message:

System.out.println("Players take turns marking a square. Only squares not already marked can be picked. Once a player has marked three squares in a row, he or she wins! If all squares are marked and no three squares are the same, a tied game is declared. Have Fun!");

This is a very long message and streaks across my screen, I want to break it up into segments so it does not break the design flow of my code. When I press enter though, Java no longer interprets the line as a string; Java believes it is a separate statement. How can I make Java interpret multiline print statements?

like image 682
chopper draw lion4 Avatar asked Dec 10 '14 19:12

chopper draw lion4


People also ask

Can Java statements span multiple lines?

A single statement can display multiple lines by using newline characters, which indicate to System.

How do I print multiple lines in system out Println?

“how to print multiple lines in java” Code Answerout. println("Players take turns marking a square." + "\nOnly squares not already marked can be picked." + "\nOnce a player has marked three squares in a row, he or she wins!"

How do you create multiple lines in Java?

If you want your string to span multiple lines, you have to concatenate multiple strings: String myString = "This is my string" + " which I want to be " + "on multiple lines."; It gets worse though. If you want your string to actually contain new lines, you need to insert \n after each line.

How do you write multiple print statements in Java?

Printing multiple values in one line on Console You can print multiple types of data by appending them using + symbol in system. out. println method in one line.


2 Answers

Are you looking for something like this?

String line = "Information and stuff" + 
          "More information and stuff " + 
          "Even more information and stuff";

System.out.println(line);
like image 153
DejaVuSansMono Avatar answered Nov 14 '22 22:11

DejaVuSansMono


Following Java's coding conventions:

System.out.println("Players take turns marking a square. "
                   + "Only squares not already marked can be picked. "
                   + "Once a player has marked three squares in a row, "
                   + "he or she wins! If all squares are marked and no "
                   + "three squares are the same, a tied game is declared. "
                   + "Have Fun!");

Always break with the concatenation operator to start the next line for readability.

https://www.oracle.com/technetwork/java/javase/documentation/codeconventions-136091.html#248

like image 33
bradylange Avatar answered Nov 14 '22 22:11

bradylange