Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/355.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 这个do while循环不起作用,我可以';我不明白为什么_Java_Do While - Fatal编程技术网

Java 这个do while循环不起作用,我可以';我不明白为什么

Java 这个do while循环不起作用,我可以';我不明白为什么,java,do-while,Java,Do While,所以我尝试制作一个程序,用户输入学生的年龄,直到输入-1。在-1之后,程序必须计算学生人数和平均年龄。 出于某种原因,我无法摆脱“边做边做”的循环。真头痛! 不管怎样,这是代码 提前谢谢 public static void main(String[] args) { // Input Scanner input = new Scanner(System.in); // Variables int escapeNumber = 0; int[]

所以我尝试制作一个程序,用户输入学生的年龄,直到输入-1。在-1之后,程序必须计算学生人数和平均年龄。 出于某种原因,我无法摆脱“边做边做”的循环。真头痛! 不管怎样,这是代码 提前谢谢

    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

}
publicstaticvoidmain(字符串[]args){
//输入
扫描仪输入=新扫描仪(System.in);
//变数
int-escapeNumber=0;
int[]studentsAge=新int[50];
做{
//输入
System.out.println(“学生年龄(类型-1至末尾):”;
//将EscapeEnumber设置为用户输入的值以中断while循环
escapeNumber=input.nextInt();
//用年龄填充数组(不能为负数)
如果(EscapeEnumber>0){
for(int-arrayPos=0;arrayPos
您有两个循环,在外部循环中只测试-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);
int-arrayPos=0;
做{
//输入
System.out.println(“学生年龄(类型-1至末尾):”;
//将EscapeEnumber设置为用户输入的值以中断while循环
escapeNumber=input.nextInt();
//用年龄填充数组(不能为负数)
if(EscapeEnumber>0&&arrayPos

我添加了另一个退出循环的条件-当数组已满。

每个循环读取2个整数,我认为这不是您真正想要的…谢谢您的帮助!