Break a programm with a loop

Asked by At

I wrote a code which calculates grades. But if I'm typing 9999 in the console, then the program should break without any output. How can I do this and which loop should I use? I tried it with a while loop but the program gives me still output.. this is my code with the while loop which doesn't work as it should. The Programm works except for the while loop. How can I do write this better?

import java.util.Scanner;
public class average {

    public static double average (double [] grade ){

        double sum = 0;
        int number = grade.length;

        for(int i = 0; i<grade.length; i++){

        double average = sum / number;
        return average;


    public static void main (String [] args){
        Scanner s = new Scanner(;
System.out.println("How much grades you add?");

int number = s.nextInt();

while(number == 9999){

double [] grade = new double [number];

System.out.println("Please enter : ");

for(int i = 0; i<grade.length; i++){
    grade[i] = s.nextDouble();
        System.out.println("My grades are: ");
        for(int i = 0; i<grade.length; i++){
            System.out.println(grade[i] + " | ");


        System.out.println("My average: " +average(grade));



2 Answers

András El Koulali On Best Solutions

You are using a break, which immediately exits only the loop. If you want to quit the program, you should use if and return like this:

if(number == 9999) {

This quits the program because with return, you exit the current function. The current function is main(), that's the program's main code. So, if you exit it, you will quit the program.

In functions with a return value (non-void functions) you need to specify the return value like this:

return 9999;

If you are on an other program thread, you need to call System.exit(0).

Reto On

You don't need to break any loop, you just need to exit the program.

if (number == 9999) {