Java 在while循环中使用System.out.format输入命令

Java 在while循环中使用System.out.format输入命令,java,Java,我编写了这个简单的java程序,但输出不正确。 我发现如果我使用System.out.println而不是System.out.format,问题就解决了。 但我想在while循环中使用System.out.format并理解为什么会发生这种情况? 这个程序从用户和排序主题中给数组成员赋值。 (我的IDE是linux中的netbeans 11.3) 输出: Enter Array length : 3 67 89 23 Enter Array member 0Enter Array membe

我编写了这个简单的java程序,但输出不正确。 我发现如果我使用System.out.println而不是System.out.format,问题就解决了。 但我想在while循环中使用System.out.format并理解为什么会发生这种情况? 这个程序从用户和排序主题中给数组成员赋值。 (我的IDE是linux中的netbeans 11.3)

输出:

Enter Array length : 
3
67
89
23
Enter Array member 0Enter Array member 1Enter Array member 2Array x = [23, 67, 89]
BUILD SUCCESSFUL in 24s

使用
\n
%n
在字符串末尾指示新行。System.out.format不像System.out.println那样创建新行

System.out.format("Array x = %s%n", Arrays.toString(x));     

使用
\n
%n
在字符串末尾指示新行。System.out.format不像System.out.println那样创建新行

System.out.format("Array x = %s%n", Arrays.toString(x));     

在while循环中,对于
System.format
方法调用,需要添加新行,使用%n触发扫描仪以获取更多输入:

while (i < n) {
    System.out.format("Enter Array member %d%n", i+1);
    x[i++] = input.nextInt();
}
while(i
在while循环中,对于
System.format
方法调用,需要添加新行,使用%n触发扫描仪以获取更多输入:

while (i < n) {
    System.out.format("Enter Array member %d%n", i+1);
    x[i++] = input.nextInt();
}
while(i
你是在问为什么它都在一条线上吗?@用户使用
%n
,而不是
\n
,因为它是平台独立的。你是在问为什么它都在一条线上吗?@用户使用
%n
,而不是
\n
,因为它是平台独立的。你的意思是输入\n:System.out.format(“输入数组成员%d\n”,i);是的,这是真的thanks@Alien_xxx转换或转义字符都可以工作。正如AndyTurner提到的,使用
%n
是一个更好的主意,因为它是独立于平台的;是的,这是真的thanks@Alien_xxx转换或转义字符都可以工作。正如AndyTurner所提到的,最好使用
%n
,因为这与平台无关。