java - 生成代码时遇到 if 和 while 循环问题

标签 java if-statement

此代码要求得分在 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);   

    }
}

最佳答案

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

由于这显然是一项硬件作业,让我尝试以这种方式帮助您:L

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

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

HTH

关于java - 生成代码时遇到 if 和 while 循环问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58224369/

相关文章:

java - Swing 布局管理器 : Maintaining uniform buttonSize while filling the whole horizontal space

java - JSF,在 session 中存储数据与 JPA L2 缓存

java - 使用 Java 为移动应用程序创建 Paypal 钱包

java - Apache POI : getNumMergedRegions

javascript - javascript (if) 语句帮助

java - 如何组织单元和集成测试?

ios - 我有一个嵌套在 for-in 循环中的 if 语句,它的计算不正确

php - 条件语句中的概率

python - 为什么 != 无法在 Python 中检查整数

c++ - if/else 的 Else 组件未执行 (C++)