#Java Syntax help

13 messages ยท Page 1 of 1 (latest)

limber mesa
#

I have written a program for the question below, but my online course moderator has asked not to use

System.exit()

please help me with this, I have just started to learn program, I need this code without using System.exit()

I am giving my code below :


import java.util.Scanner;

public class AverageOfPositiveNumbers {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        double s=0.0, k=0.0, neg=0.0, pos=0.0; double n=-1.0;
        while (n!=0) {
            n = Integer.valueOf(scanner.nextLine());
            k++;
            if (k==1 && n==0) {
                System.out.println("Cannot calculate the average");
                System.exit(0);
            } if (n<0) {
                neg++;
            } else {
                pos++;
                s = s+n;
            }
        } double avg = (s/--pos);
        if (k>1 && neg==k) {
            System.out.println("Cannot calculate the average");
        } else {
            System.out.println(avg);
        }
    }
}

I am also attaching the question:

warm sinewBOT
#

โŒ› This post has been reserved for your question.

Hey @limber mesa! Please use /close or the Close Post button above when you're finished. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

main drift
#

instead of System.exit you can use return;

past marlin
#

System.exit explicitly ends the program with the specified exit code, 0 by default

main drift
#

i meant specifically in this case.

past marlin
#

return; just stops executing the method

#

(which in this case, when on the main method, will subsequently end the program)

#

but one is not equal to the other

main drift
#

and i never said that

limber mesa
warm sinewBOT