提前致谢。当我打印这个数组的最小值时,我无法弄清楚为什么我的代码会给我带来麻烦。它似乎保留了min的初始0值,但我不确定如何纠正这个问题。 Max工作正常。我是否在程序的错误部分设置了最大值和最小值?
另外,这是我第一次使用数组,所以我可能会对稍后打印下标有一些疑问。
再次感谢!
编辑 - 据我所知,这解决了这个问题。谢谢Dan W.
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++) {
System.out.print("Enter a new number. This will continue until "
+ "you reach the size of the array. ");
arrayOfNumbers[i] = keyboard.nextInt();
}
int max = arrayOfNumbers[0];
int min = arrayOfNumbers[0];
package program8;
import java.util.Scanner;
public class arrayPrint {
public static void main(String[] args) {
final int NUMBER_OF_ELEMENTS;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the amount of numbers the array will read in. ");
NUMBER_OF_ELEMENTS = keyboard.nextInt();
int arrayOfNumbers[] = new int[NUMBER_OF_ELEMENTS];
int max = arrayOfNumbers[0];
int min = arrayOfNumbers[0];
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++) {
System.out.print("Enter a new number. This will continue until "
+ "you reach the size of the array. ");
arrayOfNumbers[i] = keyboard.nextInt();
}
for (int i = 0; i < arrayOfNumbers.length; i++) {
if (max <= arrayOfNumbers[i])
max = arrayOfNumbers[i];
}
for (int i = 0; i < arrayOfNumbers.length; i++) {
if (min >= arrayOfNumbers[i])
min = arrayOfNumbers[i];
}
System.out.print(+max+ "max and " +min+ " min");
}
}
答案 0 :(得分:1)
您输入的是什么值?由于int
的默认值为0:here
因此,如果您只输入正数,则min将始终为0.
为避免这种情况,请在用户输入数字后初始化最小值和最大值,这样最大值和最小值不会默认为0。