开发者

How do you stop a loop from running in Java

How do you stop a conditional loop from running. For example if I write an if statement that accepts values from 0 to 100. How do stop the program if a user enters a number less then 0 or above 100.

import java.util.S开发者_运维百科canner;
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);

    }
}


You use the

break;

keyword. This breaks out of a loop.


You may want to use break

for(int i=0; i<100; i++)
{
    if(user entered invalid value)
        break; // breaks out of the for loop
}


Here's a hint, since this looks like homework to me: you can either use the break keyword, or use this condition:

if (grade[index] < 0 || grade[index]> 100)
{
    // invalid grade...
}

as part of the loop condition.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜