简体   繁体   中英

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. The array will then be filled with random numbers generated from 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. 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)

Size of array to sort? 3 36,0,036,68,036,68,75, where it's supposed to just be 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 .

Move printArray(array); to the end of the loop. You might want to add a println at the end of printArray .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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