how to end a while loop with a certain variable

后端 未结 4 567
谎友^
谎友^ 2021-01-17 02:28

I am making an odd or even program with a while loop. I am trying to figure out how to end the while loop with a certain number. Right now I have 1 to continue the loop, and

4条回答
  •  无人及你
    2021-01-17 03:26

    Another thing you can try is that instead of exiting the program you can just keep asking user to enter correct input and only proceed if they do so. I don't know what is your requirement but if you want to go by good code practice then you shouldn't terminate your program just because user entered wrong input. Imagine if you googled a word with typo and google just shuts off.

    Anyways here is how I did it

    
    import java.util.Scanner;
    
    public class oddoreven {
        public static void main(String[] args) {
            int num;
            int x = 1;
            while (x == 1) {
                System.out.println("Enter a number to check whether or not it is odd or even");
                Scanner s = new Scanner(System.in);
    
                boolean isInt = s.hasNextInt(); // Check if input is int
                while (isInt == false) { // If it is not int
                    s.nextLine(); // Discarding the line with wrong input
                    System.out.print("Please Enter correct input: "); // Asking user again
                    isInt = s.hasNextInt(); // If this is true it exits the loop otherwise it loops again
                }
                num = s.nextInt(); // If it is int. It reads the input
    
                if (num % 2 == 0)
                    System.out.println("The number is even");
                else
                    System.out.println("The number is odd");
                // trying to figure out how to get the code to terminate if you put in a value
                // that isn't a number
                System.out.println("Type 1 to continue, 0 to terminate");
                x = s.nextInt();
            }
    
        }
    }
    

提交回复
热议问题