How to stop the loop from Java?

How to stop the conditional loop. For example, if I write an if , which takes values ​​from 0 to 100. How to stop the program if the user enters a number less than 0 or higher than 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); } } 
+7
source share
3 answers

You are using

 break; 

keywords. It breaks out of the loop.

+18
source

You can use break

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

Here's a tip, as it 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 a loop condition.

+1
source

All Articles