简体   繁体   中英

How can I make this code stop after the first input

    public static void main(String[] args) {

    Scanner input = new Scanner(System.in);
    while (true) {
        System.out.print("Enter your salary per hour: ");
        int salary = input.nextInt();
        
        System.out.print("Enter number of hours: ");
        int hours = input.nextInt();
        
        int sum = salary * hours;
        if (hours == 0) {
            System.out.println("Stop!");
            break;
        }
        System.out.println("Total salary " + sum);
    }
}}

I want to be able to enter numbers until I press 0, and then I want the program to stop. It stops after two zeros, but how can I make it stop after pressing only one zero? I have tried this while-if loop and different do-while loops, I just can't make it work.

Your code does exactly what you tell it to do.

You tell it to:

  • first ask for TWO numbers
  • to then compare the first number, and stop on 0

So, the solution is:

  • ask for one number
  • compare the number, stop on 0
  • ask for the second number

If you want to exit whenever you type 0 , then you have to check every value after its input.
There is the code example:

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    while (true) {
        System.out.print("What's your salary per hour? ");
        int salary = scanner.nextInt();
        if (salary == 0)
            exit();

        System.out.print("How many hours did you worked today? ");
        int hours = scanner.nextInt();
        if (hours == 0)
            exit();

        int sum = salary * hours;
        System.out.println("Your total salary is " + sum);
    }
}

private static void exit() {
    System.out.println("Have a nice day!");
    System.exit(0);
}

Please write a comment if that doesn't match your expectation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM