简体   繁体   English

在while循环中输入带有System.out.format的命令

[英]input command with System.out.format in while loop

i wrote this simple java program but output is not correct.我写了这个简单的 java 程序,但 output 不正确。 i find out that if i use System.out.println instead of System.out.format the problem solved.我发现如果我使用 System.out.println 而不是 System.out.format 问题就解决了。 but i want to use System.out.format in while loop and understand why this happened?但我想在 while 循环中使用 System.out.format 并理解为什么会这样? this program give members of an array from user and sort theme.该程序从用户和排序主题中提供数组成员。 (my IDE is netbeans 11.3 in linux) (我的 IDE 在 linux 中是 netbeans 11.3)

package array_example2;
import java.util.Scanner;
import java.util.Arrays;
public class Main { 
public static void main(String[] args) {       
    Scanner input = new Scanner(System.in);
    System.out.println("Enter Array length : ");
    int n = input.nextInt();
    int[] x = new int[n];              
    int i=0;
    while (i<n)
    {            
        System.out.format("Enter Array member %d",i);
        x[i] = input.nextInt();
        i++;
    }
    MySort.mysort(x);
    System.out.format("Array x = %s", Arrays.toString(x));        
}    

MySort class:我的排序 class:

package array_example2;
import java.util.Arrays;
public class MySort {
public static void mysort(int...a){
    Arrays.sort(a);

}

output: output:

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

Use \n or %n to indicate a new line at the end of the string.使用\n%n来指示字符串末尾的新行。 System.out.format doesn't create a new line like System.out.println does. System.out.format 不会像 System.out.println 那样创建新行。

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

In your while loop, for the System.format method call, you need to add a new line, using the %n to trigger the scanner for more input.:在您的 while 循环中,对于System.format方法调用,您需要添加一个新行,使用 %n 触发扫描仪以获取更多输入。:

while (i < n) {
    System.out.format("Enter Array member %d%n", i+1);
    x[i++] = input.nextInt();
}

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

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