简体   繁体   English

Java 回车 \r 似乎无法正常工作

[英]Java carriage return \r doesn't seem to work correctly

Here's my java code:这是我的 java 代码:

// file name is Strings.java
public class Main {
    public static void main(String[] args){
        String txt = "Hello\rWorld!";
        System.out.println(txt);

        String txt2 = "Trying\rthis";
        System.out.println(txt2);
    } 
}

And I tried to execute it from my terminal, and saw this:我试图从我的终端执行它,看到了这个:

$ java Strings.java 
World!
thisng

I have also tried to execute this from VS Code , same results.我也尝试从VS Code执行此操作,结果相同。 Does anyone know what's going on here?有谁知道这里发生了什么?

Thanks!谢谢!

——— ———

Edits:编辑:

I tried to execute something similar to (this)[https://www.w3schools.com/java/tryjava.asp?filename=demo_strings_r].我试图执行类似于 (this)[https://www.w3schools.com/java/tryjava.asp?filename=demo_strings_r] 的东西。 I know I don't have to use \r at all;我知道我根本不必使用 \r; I just wonder why the outputs are the way they are.我只是想知道为什么输出是这样的。

This depends on the operation system: Linux ( \n ), Mac ( \r ), Windows ( \r\n ).这取决于操作系统:Linux ( \n )、Mac ( \r )、Windows ( \r\n )。 All have different new line symbols.都有不同new line See Adding a Newline Character to a String in Java .请参阅Java 中的向字符串添加换行符

To get an actual combination, do use:要获得实际组合,请使用:

System.lineSeparator()

According to your example:根据你的例子:

System.out.println("Hello" + System.lineSeparator() + "World!");
System.out.println("Trying" + System.lineSeparator() + "this");

Output: Output:

$ java Strings.java 
Hello
World!
Trying
World!
this

This is a bit ugly, but a universal solution.这有点难看,但是一个通用的解决方案。

PS As alternative, you can use System.out.format() instead: PS作为替代方案,您可以使用System.out.format()代替:

System.out.format("Hello%nWorld!%n");
System.out.format("Trying%nthis%n");

PPS I think in general it is better to build a list of lines and use System.out.println() : PPS我认为一般来说最好建立一个行列表并使用System.out.println()

Arrays.asList("Hello", "World!").forEach(System.out::println);
Arrays.asList("Trying", "this!").forEach(System.out::println);

You can also use format with %n which is replaced by the platform line separator, so could use this:您还可以使用带有%nformat ,它被平台行分隔符替换,因此可以使用:

System.out.format("Hello%nWorld!%n");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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