显示答案一次

时间:2014-09-29 05:34:30

标签: java max

所以我的编程工作是创建一个读取十个用户输入的程序,然后通知用户哪一个具有最高价值。如下所示,它完美地完成了这项任务,我获得了100%的分配。

但是,我希望对编码结构进行优化,以便每次用户在提示后输入更大的值时(例如0,1,2,3,4,5,6,7,8) ,9)输出不会显示1,2,3,4,5,6,7,8和9; 9是最终输出。

如何摆脱9之前的所有值,以便输出只是9?

import java.util.Scanner;
class Army{

    public static void main(String[] args){
        // declares an array of doubles
        double[] inputArray = new double[10];
        // allocates memory for 10 doubles
        System.out.println("Please enter ten numbers.");
        try {
            Scanner in = new Scanner(System.in);
            for (int j = 0; j < inputArray.length ; j++) {
                inputArray[(int) j] = in.nextDouble();
                }
            }
            catch (Exception e) {
                e.printStackTrace();
            }

        double maxValue = inputArray[0];
        for (int i=0; i < inputArray.length; i++) {
            if (inputArray[i] > maxValue){ 
                maxValue = inputArray[i];
                System.out.println("The largest number is "+maxValue+".");
            }else{
                System.out.println("The largest number is "+inputArray[i]+".");
                // optional: display only one answer.
            }
        }
    }
}

1 个答案:

答案 0 :(得分:4)

只需更改您的代码,如下所示。

double maxValue = inputArray[0];
for (int i = 0; i < inputArray.length; i++) {
   if (inputArray[i] > maxValue) {
        maxValue = inputArray[i];
         // removed print from here
        } else {
         // removed print from here too
        }
  }
System.out.println("max value is: "+maxValue); //print max from out side the loop
相关问题