2014-09-29 121 views
1

因此,我的编程任务是编写一个程序,读取10个用户输入,然后通知用户哪个是最高值。如下图所示,它完成得很好,我在任务中获得了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. 
      } 
     } 
    } 
} 

回答

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 
+0

@PeterZēng欢迎您。 – 2014-09-29 05:55:05