作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
所以我正在尝试制作一个程序,让用户输入学生的年龄,直到输入 -1。 -1 之后,程序必须计算学生人数和平均年龄。出于某种原因,我无法摆脱 do-while 循环。真让人头疼!无论如何,这是代码
提前致谢。
public static void main(String[] args) {
// Input
Scanner input = new Scanner(System.in);
// Variables
int escapeNumber = 0;
int[] studentsAge = new int[50];
do {
// Input
System.out.println("Student's age (Type -1 to end): ");
// Set escapeNumber to what the user entered to break the while loop
escapeNumber = input.nextInt();
// Populate the array with the ages (Cannot be a negative number)
if (escapeNumber > 0) {
for (int arrayPos = 0; arrayPos < studentsAge.length; arrayPos++) {
studentsAge[arrayPos] = input.nextInt();
}
}
} while (escapeNumber != -1);
// When -1 is entered, the program goes here and makes the following
// TODO: Number of students and average age
}
最佳答案
你有两个循环,你只在外循环中测试 -1。内部 for 循环不测试 -1 输入。
消除 for 循环会更有意义:
int arrayPos = 0;
do {
// Input
System.out.println("Student's age (Type -1 to end): ");
// Set escapeNumber to what the user entered to break the while loop
escapeNumber = input.nextInt();
// Populate the array with the ages (Cannot be a negative number)
if (escapeNumber > 0 && arrayPos < studentsAge.length) {
studentsAge[arrayPos] = escapeNumber;
arrayPos++
}
} while (escapeNumber != -1 && arrayPos < studentsAge.length);
我添加了另一个退出循环的条件 - 当数组已满时。
关于java - 这个 do-while 循环不起作用,我不明白为什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27670220/
我是一名优秀的程序员,十分优秀!