简体   繁体   English

调用方法以单行打印数组

[英]Calling a method to print an array in single line

I've been trying to work out what is wrong but I can't seem to figure it out.我一直试图找出问题所在,但我似乎无法弄清楚。 Essentially my code will get the user to input N size of array.基本上我的代码会让用户输入 N 大小的数组。 The array will then be filled with random numbers generated from 1-100.然后数组将填充从 1-100 生成的随机数。 I have a printArray method which prints the elements of an array in a single line that I've tested on a fixed array and it works, but when I call it from the generated array it gives me a lot of extra 0's.我有一个 printArray 方法,它在一行中打印一个数组的元素,我已经在一个固定数组上测试过它并且它可以工作,但是当我从生成的数组中调用它时,它给了我很多额外的 0。 Here is the code:这是代码:

Scanner scan = new Scanner(System.in);
        System.out.println("Size of array:"); //prompts the user enter size of array
        int size = scan.nextInt();
        int array[] = new int[size];

for (int i = 0; i < array.length; i++) {
            array[i] = random.nextInt(100) + 1;
            printArray(array);

and here is the display method:这是显示方法:

public static void printArray(int[] array) {
    for (int i = 0; i < array.length; i++) {

        if (i == 0) {
            System.out.print(array[i]);
        }

        else if (i == array.length) {
            System.out.print(array[i]);
        }

        else
            System.out.print("," + array[i]);

    }
}

When I run the code it will generate an output like this:(3 as example)当我运行代码时,它将生成如下输出:(以 3 为例)

Size of array to sort?要排序的数组大小? 3 36,0,036,68,036,68,75, where it's supposed to just be 36,68,75. 3 36,0,036,68,036,68,75,它应该是 36,68,75。

You are printing the array multiple times in a single line.您在一行中多次打印数组。

In the first iteration you print 36,0,0 , In the second iteration you print 36,68,0 and only in the final iteration you print the fully initialized array - 36,68,75 .在第一次迭代中打印36,0,0 ,在第二次迭代中打印36,68,0并且仅在最后一次迭代中打印完全初始化的数组 - 36,68,75

Move printArray(array);移动printArray(array); to the end of the loop.到循环结束。 You might want to add a println at the end of printArray .您可能希望在printArray的末尾添加一个println

for (int i = 0; i < array.length; i++) {
    array[i] = random.nextInt(100) + 1;
}
printArray(array);

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

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