java - 你如何阻止循环在 Java 中运行

标签 java arrays loops

如何停止条件循环的运行。例如,如果我编写一个接受 0 到 100 值的 if 语句。如果用户输入小于 0 或大于 100 的数字,如何停止程序。

import java.util.Scanner;
public class TestScores {
    public static void main(String[]args) {
            int numTests = 0;
            double[] grade = new double[numTests];
            double totGrades = 0;
            double average;

            Scanner keyboard = new Scanner(System.in);

            System.out.print("How many tests do you have? ");

            numTests = keyboard.nextInt();
            grade = new double[(int) numTests];
            for (int index = 0; index < grade.length; index++) {
                    System.out.print("Enter grade for Test " + (index + 1) + ": ");
                    grade[index] = keyboard.nextDouble();                               
                    if (grade[index] < 0 || grade[index]> 100) {
                            try {
                                throw new InvalidTestScore();
                            }
                catch (InvalidTestScore e) {
                                e.printStackTrace();
                            }
                    }
            }

            for (int index = 0; index < grade.length; index++) {
                    totGrades += grade[index];
            }

            average = totGrades/grade.length;
            System.out.print("The average is: " + average);

    }
}

最佳答案

您使用

break;

关键字。这打破了一个循环。

关于java - 你如何阻止循环在 Java 中运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5006972/

相关文章:

java - Idea 中的 Tomcat。 war 爆炸 : Server is not connected. 部署不可用

带有套接字的 Java 客户端/服务器应用程序?

c++ - 在 C++ 中返回 vector 数组

string - 从分隔字符串构建对象的最佳方法(希望不是循环情况)

javascript - 在对象的对象中访问值

Java 通用列表给了我警告

java - 检查数组中是否存在字符串

ruby - 从数组中选择单个哈希,其中一个哈希元素具有最高值

c++ - 循环检查约定

java - 问题打印由定义的类构造的数组列表