do-while循环问题,但似乎无法找到它

时间:2016-01-29 23:29:04

标签: java loops java.util.scanner do-while continue

有人能告诉我我的代码有什么问题。如果用户输入一个负整数,程序应该一直告诉用户输入一个肯定的,直到他这样做。我认为这是我的do-while循环中的逻辑,但不确定。

Something is def wrong.

saveAllRecords()

3 个答案:

答案 0 :(得分:1)

尝试使用&&而不是||像这样:

  } while (!isNumber && !isNumPos);

答案 1 :(得分:1)

我想知道这会更容易吗? :)

private static Scanner input = new Scanner(System.in);

public static void main(String[] args) {

    int numberOne = 0;
    int numberTwo = 0;

    boolean flag = true;

    System.out.println("Enter a positive number: ");
    numberOne = input.nextInt();

    System.out.println("Enter another positive number: ");
    numberTwo = input.nextInt();

    while (flag) {

        if (numberOne > 0 && numberTwo > 0) {
            flag = false;
        } else if (numberOne <= 0) {
            System.out.println("First number was invalid, please enter a positive number: ");
            numberOne = input.nextInt();
            flag = true;
        } else if (numberTwo <= 0) {
            System.out.println("Second number was invalid, please enter a positive number: ");
            numberTwo = input.nextInt();
            flag = true;
        }

    }

    System.out.println("Your numbers were " + numberOne + " and " + numberTwo);
}

答案 2 :(得分:0)

我稍稍调整了你的代码。但是,有更简单的方法可以做到这一点。

do {
    System.out.print("Enter a positive integer: ");
    firstN = input.nextInt();
    isNumber = true;

  if (firstN > 0) {
    isNumPos = true;
    isNumber = true;
    break;
  } else { 
    isNumPos = false;
    isNumber = false;
    continue;
  }
} while (!(isNumber) || !(isNumPos));


do {
    System.out.print("Enter another positive integer: ");
    secondN = input.nextInt();
    isNumber = true;

  if (secondN > 0) {
    isNumPos = true;
    isNumber = true;
  } else {
    isNumPos = false;
    isNumber = false;
  }

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