【发布时间】:2016-07-24 21:46:14
【问题描述】:
因此,我的任务是创建一个代码,该代码创建一个预先确定的数组列表,供用户输入多达 100 多个整数,并且可以选择使用 0 来表示一旦完成输入。但是,当试图调用最小值时,它只返回一个值 0。我将如何正确格式化它以便将它与用户输入的数组列表中的所有值进行比较?感谢我能得到的任何帮助!我在旁边添加了 cmets,以显示我对哪些方面有疑问或我认为错误在哪里。
public static void main(String[] args) {
Scanner TextIO = new Scanner(System.in);
String calc;
double[] numbers2; //An array for storing double values.
int[] numbers; // An array for storing the int values.
int count; // The number of numbers saved in the array.
int num; // One of the numbers input by the user.
int max;
int min;
/* Initialize the summation and counting variables. */
numbers2 = new double[100]; // Space for 100 doubles.
numbers = new int[100]; // Space for 100 ints.
count = 0; // No numbers have been saved
max = Integer.MIN_VALUE; //Properly initialized?
min = Integer.MAX_VALUE; //Properly initialized?
/*Start of min method. */
if (calc.equals("min")){
System.out.println("Enter up to 100 positive integers;
while (true) { // Get the numbers and put them in the array.
System.out.print("-> ");
num = TextIO.nextInt();
if (num <= 0) {
break; } /*Zero marks the end of the input. All
have been inputted. */
else {
numbers[count] = num; // Put num in position count.
count++;
}
for (int i=0; i<numbers.length;i++) { //"For" statement needed here?
if (numbers[i] < min) {
min = numbers[i];}
}
}
System.out.println("Your minimum is : " + min);
}
}
}
【问题讨论】:
-
最多超过 100 个 - 这是什么意思??
-
只是想一想,您也可以将 min 和 max 指定为数组中的第一项,但我认为 MIN 和 MAX 也可以。
-
int[100]有 101 个整数的空间。 -
你的格式很糟糕。
-
用
min = Math.min(min, num);替换你的for循环。
标签: java arrays arraylist max minimum