关于排序数字的新手java代码

时间:2016-04-17 02:51:04

标签: java

这是我在课堂上工作的代码。我会问我的老师,但今天是星期天。

好吧,直接蝙蝠,我需要对一些数字进行排序并找到最高数量和最低数量。

那么什么有效,什么无效?

代码在iMax变量下找到最大数字。通过调整新变量名称iMin和< (较小的标志)它应该给我最低的数字,但它没有,这就是问题所在。相反,它告诉我0.0,这不是我可以选择的众多随机数之一。说白了,数字1000,2000,3000,4000,5000。它告诉我5000是最高数字,0.0是最低数字。 0.0不是我的一个号码而且我已经摸不着头脑了,请帮助我解决这个问题,因为它让我爬上了墙。所以这里是代码:

import java.util.Scanner;
public class JustWork {

    public static void main(String[] args) {
        double [] run1 = new double[7];
        double iMax = run1[0];
        double iMin = run1[0];

        Scanner input = new Scanner(System.in);

        for (int i = 0; i<run1.length; i++)
        {
            System.out.println("Score from Judge " + (i+1) + ": ");
            run1[i] = input.nextDouble();   
        }

        for (int i = 1; i<run1.length; i++)
        { if (run1[i]< iMin)
            iMin = run1[i];
        }

        for (int i = 1; i<run1.length; i++)
        { if (run1[i]> iMax)
            iMax = run1[i];
        }


        System.out.println("the minimum score is: " + iMin);

        System.out.println("the maximum score is: " + iMax);
    }
}

例如,如果我输入以下数字:3,4,5,6,7,8,9 System.out.prints out this:

Score from Judge 1: 
3
Score from Judge 2: 
4
Score from Judge 3: 
5
Score from Judge 4: 
6
Score from Judge 5: 
7
Score from Judge 6: 
8
Score from Judge 7: 
9
the minimum score is: 0.0
the maximum score is: 9.0

2 个答案:

答案 0 :(得分:3)

初始化双数组时,默认情况下,它们为每个元素分配0。然后,当您指定run1[0] to iMin and iMax时,您已经将0设置为隐式。 为了获得这一点,只需在获得输入后分配初始值

public static void main(String[] args) {
    double [] run1 = new double[7];
    Scanner input = new Scanner(System.in);

    for (int i = 0; i<run1.length; i++)
    {
        System.out.println("Score from Judge " + (i+1) + ": ");
        run1[i] = input.nextDouble();   
    }

    double iMax = run1[0];
    double iMin = run1[0];
    for (int i = 1; i<run1.length; i++)
    { if (run1[i]< iMin)
        iMin = run1[i];
    }

    for (int i = 1; i<run1.length; i++)
    { if (run1[i]> iMax)
        iMax = run1[i];
    }
    System.out.println("the minimum score is: " + iMin);
    System.out.println("the maximum score is: " + iMax);
}

答案 1 :(得分:2)

在第一个iMin循环之后初始化iMaxfor 。之前初始化时,值为0

double [] run1 = new double[7]; // <-- an array of 7 elements, all 0.0 
// double iMax = run1[0];       // <-- 0.0
// double iMin = run1[0];       // <-- 0.0
Scanner input = new Scanner(System.in);
for (int i = 0; i < run1.length; i++)
{
    System.out.println("Score from Judge " + (i+1) + ": ");
    run1[i] = input.nextDouble();   
}    
double iMax = run1[0];
double iMin = run1[0];