简体   繁体   中英

Looping for odd and even number in java

how do i repeatedly ask the user to enter an input until the user enters a negative number. If the user enters a negative number or 0, the program will end?

import java.util.Scanner;
public class OddEvenInt {

    public static void main(String args[]) {

        Scanner s = new Scanner(System. in );
        int x;

        do {
            System.out.println("Enter an integer to check if it is odd or even ");
            x = s.nextInt();

            if (x % 2 == 0)
                System.out.println("You entered an even number.");
            else
                System.out.println("You entered an odd number.");
        } while (x % 2 == 0);
    }
}

您必须更改while子句:

while (x>0)

use < and >

public static void main(String[] arguments) {
    Scanner s = new Scanner(System.in);
    int x = 0;

    do {

        System.out.println("Enter an integer to check if it is odd or even ");

        try {
            x = Integer.parseInt(s.nextLine());
            if (x > 0) {
                System.out.println("You entered an even number.");
            } else if (x == 0) {
                System.out.println("You entered 0, thats not negativ or positiv.");
            } else {
                System.out.println("You entered an odd number.");
            }

        } catch (Exception e) {
            //e.printStackTrace();
            System.out.println("U call this an Integer? :P");
        }

    } while (x > 0);
    return;
}

last edit: check if your input is numberic, if you want to check the error you can remove // from the catch-block

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