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

标签 java sorting methods

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

import java.util.Scanner;

public class Sorting {

static int d = 0;
static int c = 0;
static int n = 0;
static int swap = 0;
static int array[] = new int[n];

public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);

    System.out.print("Number of elements: ");
    n = scan.nextInt();



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

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

    static void BubbleSort(int[] a) { //this line!!

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

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

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

最佳答案

很难理解你在问什么:

  • BubbleSort 方法采用 int[] a 参数,但从不使用它
  • main 方法将数字读取到数组中,但从不调用 BubbleSort
  • 您询问的是 BubbleSort 的返回值,但该方法被声明为 void,并且它修改了 array 的内容,一个静态变量:这个方法似乎并不打算返回任何东西,而是就地对数组进行排序
  • 许多未使用的变量
  • 许多变量在类中声明为静态,但它们可以是方法中的局部变量,其中一些在 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] + " ");
        }
    }
}

关于java - 在方法外部定义变量并获取其返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33400759/

相关文章:

java - 如何从 base64 编码的字符串构造 java.security.PublicKey 对象?

c++ - 后缀运算符重载中虚拟参数的用途? C++

mongodb - 如何映射减少组、排序和计数排序值

Python - 按字母顺序排列嵌套列表

java - 从父类(super class)调用方法的 super 关键字与类名之间的区别

ios - 如何将 didSelectViewController 与两个不同的 Controller 一起使用?

java - 如果用户单击 IE Pane ,IE 中的模式对话框将隐藏在 IE 后面

java - ArrayList<ArrayList<String>> 内存不足(Java 堆空间)。还有其他选择吗?

c# - 将父类(super class)转换为特定的派生类型

c++ - 使用指针而非迭代器删除 std::list 中的元素