简体   繁体   中英

How can I print a result from a void method

I'm doing an assignment for my intro to programming class and it's a bubble sort. The code may be flawed, but I'm not looking for someone to solve that problem. What my problem is, is that I'm trying to print it. I've been given the condition that the method had to be defined by a void method by the line "public static void sort(int[] array)". So, if I tried import Arrays, and used System.out.println(Arrays.toString(sort(array))); in my main method, it wouldn't work because I get a compiler error saying that void does not apply. If I tried to put it into a loop at the main method, it tells me that there are incompatible types. What is found is a void, what is required is an int[], but the original condition of the assignment is to use a void method. So, with that being said, should I change the method from void to int[] for testing purposes and submit the assignment as a void, or is there a way to print the output of this code with the void and I'm just missing it?

public static void sort(int[] array)
      { 
        int[] y = new int[array.length];
        for(int i = 0; i<=array.length-1; i++)
        {
          for(int j = i+1; i<=array.length-1; j++)
          {
            if(array[i] < array[j]){
              y[i] = array[j];
            }
            if(array[i] >= array[j]){
              y[i] = array[i]; 
          }  
        }
          for(int k = 0; k<y.length; k++){
          System.out.println(y[k]);
          }
      } 
    } //end of sort method

The problem is that you create an new local array inside your sort method which you obviously cannot return because of the restriction of you assignment.

int[] y = new int[array.length];

Your method will not be valid, since the array passed will remain unchanged. You need to do the sorting in place, ie without creating a new array. So that if you pass it from your main method, it gets sorted and you can print it there.

Bubble sort should use a swap method, so you just need one temporary variable.

In order to print the array, in your main method you'll need

//code that initializes the array or whatever
sort(myArray);
System.out.println(Arrays.toString(myArray)); //print the array modified by the previous method call

Also note what @A4L said about your local array. Work with the array you pass as parameter to your method, don't create a new one.

Arrays.sort()修改您传入的数组。因此,如果您遍历该array对象并在调用Arrays.sort()之后打印元素,它将为您打印。

Since you have a void sort method, you want it to sort the array as a side effect. That is, modify the values in the int[] array reference you passed as a method parameter. Then you can print it from main.

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