I have string like
\"I am a boy\".
I want to print like this way
\"I
am
a
boy\".
Can anybody help me?<
Try:
System.out.println("I\nam\na\nboy");
Full program example, with a fun twist:
Open a new blank document and save it as %yourJavaDirectory%/iAmABoy/iAmABoy.java
. "iAmABoy" is the class name.
Paste the following code in and read through it. Remember, I'm a beginner, so I appreciate all feedback!
//The class name should be the same as your Java-file and directory name.
class iAmABoy {
//Create a variable number of String-type arguments, "strs"; this is a useful line of code worth memorizing.
public static void nlSeparated(String... strs) {
//Each argument is an str that is printed.
for (String str : strs) {
System.out.println(str);
}
}
public static void main(String[] args) {
//This loop uses 'args' . 'Args' can be accessed at runtime. The method declaration (above) uses 'str', but the method instances (as seen below) can take variables of any name in the place of 'str'.
for (String arg : args) {
nlSeparated(arg);
}
//This is a signature. ^^
System.out.print("\nThanks, Wolfpack08!");
}
}
Now, in terminal/cmd, browse to %yourJavaDirectory%/iAmABoy
and type:
javac iAmABoy.java
java iAmABoy I am a boy
You can replace the args I am a boy
with anything!
If you simply want to print a newline in the console you can use ´\n´ for newlines.
If you want to break text in swing components you can use html:
String s = "<html>first line<br />second line</html>";
I use this code String result = args[0].replace("\\n", "\n");
public class HelloWorld {
public static void main(String[] args) {
String result = args[0].replace("\\n", "\n");
System.out.println(result);
}
}
with terminal I can use arg I\\nam\\na\\boy
to make System.out.println
print out
I
am
a
boy
System.out.println("I\nam\na\nboy");
System.out.println("I am a boy".replaceAll("\\s+","\n"));
System.out.println("I am a boy".replaceAll("\\s+",System.getProperty("line.separator"))); // portable way
You can also use System.lineSeparator():
String x = "Hello," + System.lineSeparator() + "there";