【问题标题】:First do-while loop not functioning properly第一个 do-while 循环无法正常运行
【发布时间】:2024-01-17 20:34:01
【问题描述】:

我的代码似乎有问题。我的代码检测到非整数并不断要求用户输入一个正数,但是当你插入一个负数时,它只要求用户输入一个正数一次。怎么了?肯定有我的 do-while 循环。 我只关注第一个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);
}

}

【问题讨论】:

  • 它对负整数、负小数或两者都有故障吗?
  • 负整数。

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


【解决方案1】:

在这种情况下,您读取了两次输入:

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

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

【讨论】:

    【解决方案2】:

    试试这段代码

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

    【讨论】:

      最近更新 更多