gpt4 book ai didi

java - 第一个 do-while 循环无法正常运行

转载 作者:行者123 更新时间:2023-12-01 10:30:59 26 4
gpt4 key购买 nike

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

}

最佳答案

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

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

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

关于java - 第一个 do-while 循环无法正常运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35093709/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com