所以我的教授让我们做了一项任务,要求用户提供5个有效(51-99)和唯一(非重复)的数字。我只是无法弄清楚为什么我在while循环中嵌套for循环没有递增i
,我怀疑它是break;
但没有那个for循环保持循环。任何帮助都是极好的。谢谢。
public static void main(String[] args) {
int[] userArray;
userArray = new int[5];
int real = 0;
System.out.println("Please print out 5 numbers between 50 and 100. ");
Scanner entry = new Scanner(System.in);
while (real < 5) {
int count = entry.nextInt();
boolean aCount = isValid(count);
if (aCount == true) {
for (int i =0; i < userArray.length; i++) {
userArray[i] = count;
real++;
break;
}
} else {
System.out.println("That is not a valid number.");
}
}
}
public static boolean isValid(int a) {
if (a > 50 && a < 100) {
return true;
} else {
return false;
}
}
答案 0 :(得分:2)
我知道了!我只需要删除for循环并将其放入:
userArray[i] = count;
i++;
real++;
谢谢schmidt73和所有帮助过的人!
答案 1 :(得分:1)
int i=0;
while (real < 5) {
int count = entry.nextInt();
boolean aCount = isValid(count);
if (aCount == true) {
userArray[i++] = count;
real++;
} else {
System.out.println("That is not a valid number.");
}
}
我想这就是你要做的事。
答案 2 :(得分:0)
首先,您还需要测试数组是否包含您要添加的值(在验证中)。你可以做点什么
public static boolean isValid(int[] arr, int real, int a) {
if (a > 50 && a < 100) {
for (int i = 0; i < real; i++) {
if (arr[i] == a) {
return false;
}
}
return true;
}
return false;
}
然后您的main
方法可能会写成
int[] userArray = new int[5];
int real = 0;
System.out.println("Please print out 5 numbers between 50 and 100. ");
Scanner entry = new Scanner(System.in);
while (real < 5) {
int count = entry.nextInt();
if (isValid(userArray, real, count)) {
userArray[real++] = count;
} else {
System.out.println("That is not a valid number.");
}
}
System.out.println("The array contains: " + Arrays.toString(userArray));