简体   繁体   中英

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

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?

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);

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

在你想要换行的地方添加 '\\n'。

你可以输入: System.out.println("这是第一行\\n" + "这是第二行")


System.out.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!"
+ "\nIf all squares are marked and no three squares are the same, a tied game is declared."
+ "\nHave Fun!");

Done.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM