有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java第一个dowhile循环运行不正常

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

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) 个答案

  1. # 1 楼答案

    试试这段代码

    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;
      }
    }
    
  2. # 2 楼答案

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

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

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