While循环不起作用

一日游

嗨,我是Java的新手,并通过在线练习来熟悉它。我如何正确编码while循环,以便每次用户输入错误时,它都会再次询问相同的问题,而不会继续进行下一行代码

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Array {
    public static void main(String[] args) {
        Scanner dataIn = new Scanner(System.in);
        int entries = 0;
        List<Integer> grade = new ArrayList<Integer>();

        System.out.println("Enter number of students? ");
        entries = dataIn.nextInt();
        boolean checker = true;
        while (checker){
        for (int i = 0; i < entries; i++){

            int input;
            int addToList;
            System.out.println("Enter grade for student: ");
            input = dataIn.nextInt();
            grade.add(input);

            if (input >= 0 && input<= 100) {

            }else {
                System.out.println("invalid input try again..");
                checker = false;
            }
        }
        }

        int sum = 0;
        int count = grade.size();
        double mean;
        for (int grades : grade){
            sum+= grades;
        }
        mean =(double)sum/count;

        System.out.println("The Grades are: " + grade);
        System.out.println("The number of elements in the Array is " + grade.size());
        System.out.println("The average is: " + mean);
    }
}
学徒

您的逻辑是倒退。如果输入不正确,则希望循环继续。有两种方法可以解决此问题:

  1. 更改while(checker)while(!checker)

  2. 打印错误消息后,请更改checker=falsechecker=true并设置checker=falseif分支中。

如果将checker变量名更改为更直接读取的名称,则可能会有所帮助例如,isInputCorrect当您编写时,阅读非常好,while(!isInputCorrect)并且还使true的值更加清楚false

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

While循环不起作用

来自分类Dev

For 循环不起作用但 while 循环起作用

来自分类Dev

Realloc在while循环中不起作用

来自分类Dev

使用if语句的while循环不起作用

来自分类Dev

通过XPathNodeIterator的while循环不起作用

来自分类Dev

StreamReader的While循环不起作用

来自分类Dev

UILongPressGestureRecognizer中的While循环不起作用

来自分类Dev

while循环更新查询不起作用

来自分类Dev

jQuery while循环不起作用

来自分类Dev

while循环在Java中不起作用

来自分类Dev

/ while循环不起作用吗?

来自分类Dev

C- While循环不起作用

来自分类Dev

Python while循环迭代不起作用

来自分类Dev

为什么while循环不起作用?

来自分类Dev

简单的while循环不起作用

来自分类Dev

Implode() 在 While 循环中不起作用

来自分类Dev

C# while 循环不起作用

来自分类Dev

在while循环内查询不起作用

来自分类Dev

PHP While循环中的While循环不起作用

来自分类Dev

C while循环无限循环EOF不起作用

来自分类Dev

For循环不起作用

来自分类Dev

For 循环不起作用

来自分类Dev

for 循环不起作用

来自分类Dev

循环不起作用

来自分类Dev

While循环和Jquery追加不起作用

来自分类Dev

Java中的嵌套while循环不起作用

来自分类Dev

do-while循环似乎不起作用(Java)

来自分类Dev

While循环仅创建3个对象不起作用

来自分类Dev

while循环代码不起作用(keepgoing ='y')