Incursion
Incursion

Reputation: 23

Can't figure out of how to stop the application when a specific String value match a specific condition

It's my first time posting some topic on this website, and running on a problem that I can't get over it. The following problem that I'm stunning into is as followed:

When the total calculation of the above decimal numbers meets a specific target amount, print: "Congratulations" if not, print:"Calculation error", after they input the string word: "Ready". when a user inputs a string called: "I Quit!", the application will exit and prints: "Quitter".

Here is the Java code that I currently have:

public static void goal(double targetAmount) {
    Scanner sc = new Scanner(System.in);

    double total = 0;

    while (scanner.hasNextDouble()) {
        double input= sc.nextDouble();
        total += input;
    }


    String inputString = sc.next();     
}

I'm looking forward to see your response. Hope I've formulate my question properly?

Upvotes: 2

Views: 98

Answers (2)

Tobias
Tobias

Reputation: 2575

I think the problem is the input you read using scanner.next(), because scanner.next() reads the input till the next blank character. Which means it will just read I when you enter I Quit!.

Printing the output of the variable input shows the problem:

public static void main(String[] args) {
    salarisdoel(100);
}

public static void salarisdoel(double targetAmount) {
    Scanner scanner= new Scanner(System.in);

    double total = 0;

    while (scanner.hasNextDouble()) {
        double inputMoney= scanner.nextDouble();
        total += inputMoney;
    }


    String input = scanner.next();
    System.out.println(input);//print to check what was read from the console
    switch (input) {
        case "I Quit!":
            System.out.println("Quitter");
            break;
        case "Ready":
            if (total>= targetAmount) {
                System.out.println("Congratulations");
            } else {
                System.out.println("Calculation Error");
            }
            break;
        default: 
            System.out.println("Something went wrong. Try again!");
            break;
    }     
}

If you use a string without a blank space for quitting (e.g. "I_Quit!") it will work.

Upvotes: 2

Smile
Smile

Reputation: 4088

You can use System.exit() to exit the program.

 case "I Quit!":
   System.out.println("Quitter");
   System.exit();

Upvotes: 2

Related Questions