【问题标题】:adding elements to an array and call sort method将元素添加到数组并调用排序方法
【发布时间】:2014-03-10 18:32:58
【问题描述】:

我在尝试将 50 个元素从我的文件加载到数组并调用冒泡排序时遇到了困难。有人可以告诉我我做错了什么。我已经将整个列表加载到一个数组中。只需从中挑出50个第一个或随机元素并调用bubbleSort方法即可。

public class Sorts
{
    public static int bubbleCount = 0;

    public static void bubbleSort(double data[], int count)
    {
        int pass, i; 
        double temp;
        boolean done;
        done = false;
        for (pass = 0; !done; pass++)
        { 
            done = true;
            for (i = 0; i < count - 1 - pass; i++)
            {
                bubbleCount++;
                if (data[i] > data[i+1])
                {
                    temp = data[i];
                    data[i] = data[i+1];
                    data[i+1] = temp;
                    done = false;
                }
            }
        }
    }
}

这是我的主要课程

public class MainSort
{
    static File numData;
    static Scanner s;
    public static void main(String[] args) throws FileNotFoundException 
    {
        numData = new File("Num.dat");   
        try 
        {
            s = new Scanner(numData);
        } catch (FileNotFoundException e) {
        }
        double[] array = new double[1];
        while(s.hasNext())
        {
            int i=0;
            array[i]=s.nextDouble();
            //print
            //System.out.println(array[i]);
            i++;
        }
        Sorts sorted = new Sorts();
        sorted.bubbleSort(array[50]);

    }
}

【问题讨论】:

  • 你有什么“困难”?
  • 在下面 2 个 cmets 的帮助下,我修复了数组部分。我确实得到了一个数组索引超出范围的异常,因为该列表中有数千个元素。另外我仍然不能调用我的 bubbleSort 方法。它告诉我它需要 double[],int 类型,但找到了 double 类型。原因:实际参数列表和形式参数列表的长度不同。

标签: java sorting bubble-sort


【解决方案1】:

在循环外声明变量int i

      int i=0;

     while(s.hasNext()){
            array[i]=s.nextDouble();
            //print
            //System.out.println(array[i]);
            i++;
            }

【讨论】:

    【解决方案2】:

    问题在于这段代码

    int i=0;
    array[i]=s.nextDouble();
    

    您在 while 循环中声明了 int i = 0; var。每次它被设置为0。 所以在数组中,每次索引 0 处的值都会被新值替换。

    声明int ioutside whileloop。

    int i = 0;
    while(s.hasNext()) {
      array[i]=s.nextDouble();
      i++;
    }
    

    【讨论】:

      猜你喜欢
      • 2012-06-03
      • 1970-01-01
      • 1970-01-01
      • 2019-05-27
      • 2018-08-31
      • 1970-01-01
      • 2019-05-03
      • 1970-01-01
      相关资源
      最近更新 更多