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++){
            sum+=grade[i];
        }

        double average = sum / number;
        return average;

    }

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

int number = s.nextInt();

while(number == 9999){
    break;
}

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("");
        System.out.println("My average: " +average(grade));

    }

}

2 Answers

1
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) {
    return;
}

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).

1
Reto On

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

if (number == 9999) { 
   System.exit(); 
}