第一个do-while循环不能正常运行

时间:2016-01-29 20:43:52

标签: java if-statement boolean do-while boolean-logic

我的代码似乎有些东西。我的代码检测到非整数,并不断要求用户输入一个正#,但是当你插入一个负#时,它只是要求用户只输入一次正数。怎么了?肯定有我的do-while循环的东西。 我只关注第一个N,然后我可以做第二个N.

import java.util.Scanner;

public class scratch {

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);

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

    System.out.print("Enter a positive integer: ");

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

        }

    } while (!(isNumber) || !(isNumPos));

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

    } while (!(isNumber) || !(isNumPos));

    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);
}

}

2 个答案:

答案 0 :(得分:1)

在这种情况下你读了两次输入:

        firstN = input.nextInt();
        ...
        input.next ();

添加一些指示变量或重新组织代码,以便在您通过第一次阅读时阅读,避免使用第二个。

答案 1 :(得分:0)

试试这段代码

while (true){
  System.out.println("Please enter Positive number");
  boolean hasNextInt = scanner.hasNextInt();
  if(hasNextInt){
    int firstNum = scanner.nextInt();
    if(firstNum>0){
      break;
    }else{
      continue;
    }
  }else{
    scanner.next();
    continue;
  }
}