仅接受使用while循环或任何其他的正整数

时间:2016-01-28 07:34:03

标签: java algorithm java.util.scanner user-input do-while

我的程序当前拒绝除整数之外的任何输入,但我试图更进一步,让它只接受正整数。我将如何实现这一目标。我尝试创建另一个布尔值并将其称为numisGreat,并为此部分调用另一个do-while循环,但我似乎无法得到它。

import java.util.Scanner;

public class TandE {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        int firstN = 0;
        int secondN = 0;
        boolean isNumber = false;
        boolean numisGreat = false;

        System.out.print("Enter a positive integer: ");
        do {
            if (input.hasNextInt()) {
                firstN = input.nextInt();
                isNumber = true;
            } else {
                System.out.print("Please enter a positive integer: ");
                isNumber = false;
                input.next();
            }

        } while (!(isNumber));

        System.out.print("Enter another positive integer: ");
        do {
            if (input.hasNextInt()) {
                secondN = input.nextInt();
                isNumber = true;
            } else {
                System.out.print("Please enter a positive integer: ");
                isNumber = false;
                input.next();
            } 

        } while (!(isNumber));

        System.out.println("The GCD of " + firstN + " and " + secondN + " is " + gCd(firstN, secondN));

    }

    public static int gCd(int firstN, int secondN) {
        if (secondN == 0) {
            return firstN;
        } else
            return gCd(secondN, firstN % secondN);
    }

}

1 个答案:

答案 0 :(得分:1)

只需添加一个测试输入数字是否为正的条件:

boolean isPosNumber = false;
do {
    if (input.hasNextInt()) {
        firstN = input.nextInt();
        if (firstN > 0) {
            isPosNumber = true;
        } else {
            System.out.println("You entered a non-positive number, try again: ");
        }
    } else {
        System.out.print("Please enter a positive integer: ");
        isPosNumber = false;
        input.next();
    }

} while (!isPosNumber);