在方法外定义变量并获取其返回值

时间:2015-10-28 20:14:02

标签: java sorting methods

正如标题所说的那样。我必须编写一个代码来运行所有三种排序方法(冒泡,插入,选择)。到目前为止,我已准备好泡沫部分,但我不知道如何使其工作,因为当您声明方法以便获得返回值时必须定义变量。但我需要它来返回在方法外定义的变量。有没有可能的方法呢?请记住,我还需要在另外两种方法中再次使用相同的值。

import glob
# stuff
if not glob.glob('*.true')`:
    # do stuff if no file ending in .true exists

3 个答案:

答案 0 :(得分:2)

在方法的顶部添加:

int[] b = Arrays.copyOf(a, a.length);

注意:为了让阵列再使用两次,这是必要的。

现在您有了一个新数组,您可以对b进行操作,而不会影响为a传入的数组。您可以将标题更改为static int[] BubbleSort(int[] a),最后更改为return b;

答案 1 :(得分:2)

很难理解你在问什么:

  • BubbleSort方法采用int[] a参数,但从不使用
  • main方法将数字读入数组,但从不调用BubbleSort
  • 您询问的是BubbleSort的返回值,但该方法已声明为void,并且它修改了array的内容,static变量:它似乎这个方法不是为了返回任何东西,而是对数组进行就地排序
  • 许多未使用的变量
  • 许多变量在类中声明为static,因为它们可能是方法中的局部变量,其中一些变量是for循环中的局部变量

修复上述问题后, 你的实现会更有意义:

import java.util.Scanner;

public class Sorting {

    public static void main(String[] args) {

        int n, c;
        Scanner scan = new Scanner(System.in);

        System.out.print("Number of elements: ");
        n = scan.nextInt();
        int[] array = new int[n];

        System.out.print("Enter " + n + " elements: ");

        for (c = 0; c < n; c++) {
            array[c] = scan.nextInt();
        }

        BubbleSort(array);
    }

    static void BubbleSort(int[] array) {

        int n = array.length;

        for (int c = 0; c < (n - 1); c++) {
            for (int d = 0; d < n - c - 1; d++) {
                if (array[d] > array[d + 1]) {
                    int swap = array[d];
                    array[d] = array[d + 1];
                    array[d + 1] = swap;
                }
            }
        }

        System.out.print("Bubble sort: ");

        for (int c = 0; c < n; c++) {
            System.out.print(array[c] + " ");
        }
    }
}

答案 2 :(得分:-2)

CREATE TRIGGER trg_update_city_state on dbo.locationTbl AFTER Update AS BEGIN UPDATE locationTbl SET locationTbl.city = zipTbl.city, LocationTbl.stateCode = zipTbl.stateCode, locationTbl.salesTaxRate = zipTbl.salesTaxRate FROM zipTbl END 方法无法返回值。如果您希望void传递给int[] a,已排序,然后返回,则标题应如下所示:

BubbleSort()

该方法还需要以return语句结束:

static int[] BubbleSort(int[] a) {
相关问题