【问题标题】:Having trouble with if and while loops when generating code生成代码时遇到 if 和 while 循环问题
【发布时间】:2019-10-03 17:45:26
【问题描述】:

此代码要求的分数在 0-100 之间。如果分数介于两者之间,则将其添加到总分中,然后用于计算平均值。我遇到的问题是如果分数大于 100 则放置 if 语句,打印非法语句并要求用户重新输入数字。当我把这个 if 放在 while 循环中时,我会打印出无限数量的非法异常。我该如何解决这个问题?

public class SentinalValuedControlledLoop {

    public static void main(String[] args) {
        int studentCount = 1;
        double total = 0.0;
        double average;
        int score;

        Scanner stdin = new Scanner(System.in);

        //title at top of output
        System.out.println("Sai Bharathula's Score Report");

        //read score for student
        System.out.printf("Enter a score (0 too 100, -1 to quit #%d:)", studentCount);
        score = stdin.nextInt();


        while(score !=-1) {
           //THIS IS THE IF STATEMENT I AM TALKING ABOUT THAT IS CAUSING ME TROUBLE 
            if(score >100){
                System.out.println("Illegal Score Try Again");
            }

            if(score >0 && score <= 100) {
               System.out.printf ("Enter a score (0 too 100, -1 to quit #%d:)", studentCount);
              score = stdin.nextInt();         
              studentCount++;  
            }
        }

    average = total / studentCount;
    System.out.printf ("\nThe average score for %d students is %8.2f\n",
                          studentCount, average);   

    }
}

【问题讨论】:

  • 如果输入的数字大于100,则需要从用户那里获取一个新的数字。你没有这样做,所以score 永远保持在那个初始值,让你的代码陷入无限循环。

标签: java if-statement


【解决方案1】:

您的问题是无限循环的经典示例。

既然这显然是一个硬件作业,让我试着用这种方式帮助你:L

  • 当分数大于 100 时,有什么方法可以终止循环?
  • 换句话说:您进入循环的分数为例如101
  • 然后检查“如果”
  • 然后打印消息
  • 接下来会发生什么?循环再次开始。

即你必须做一些事情来“逃离”循环。

HTH

【讨论】:

    【解决方案2】:

    您需要接受输入,直到满足您的退出条件(分数 == -1)。如果违反了您的验证条件(分数 100),您应该再次提示用户输入。

    最简单的方法是使用 do-while 循环并添加 if 语句进行验证:

    int score = 0;
    do {
            System.out.printf("Enter a score (0 too 100, -1 to quit #%d:)", studentCount);
            score = stdin.nextInt();         
            if (score > 100 || score < -1) {
                System.out.println("Illegal Score Try Again");
                continue;
            }
            studentCount++;
            total += score;
    } while (score != -1);
    

    P.S:您没有在循环中将分数添加到运行总分中。补充说。

    【讨论】:

    • 太棒了。如果对您有所帮助,请随时接受答案。干杯
    猜你喜欢
    • 1970-01-01
    • 2017-06-02
    • 1970-01-01
    • 1970-01-01
    • 2021-07-25
    • 1970-01-01
    • 1970-01-01
    • 2013-04-13
    • 2014-01-16
    相关资源
    最近更新 更多