所以我的编程任务是编写一个程序,读取十个用户输入,然后通知用户哪一个输入的值最高。如下图所示,它完美地做到了这一点,我 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.
}
}
}
}
最佳答案
只需按如下方式更改您的代码。
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
关于java - 显示一次答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26093109/