How to use line break argument

  • A+
Category:Languages

I wrote the most simple helloworld.

public class Helloworld {      public static void main(String[] args) {         System.out.println("Hello/nHello");     } } 

when it run ,the result is

Hello Hello 

But if I use Hello/nHello as arguments

public class Helloworld {      public static void main(String[] args) {         System.out.println(args[0]);     }  } 

the result is Hello/nHello.How to get the two line result? Thx.

 


When you define a String as "Hello/nHello" in Java, it contains no '/' character. It is an escape sequence for the line break: "/n" is just one character. When you use this string as an argument to your program, however (so the string is defined outside), "/n" is interpreted as two characters: '/' and 'n'. You have to replace these two characters with the line break, knowing that to match '/' you have to escape it with '/':

System.out.println(args[0].replace("//n", "/n")); 

For portability concerns, you can also use System.lineSeparator() as the replacement string.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: