我的do while循环只发生一次,即使我第二次输入了相同的值.为什么会这样


Scanner sc1 = new Scanner(System.in);
System.out.print("Enter prime p value up to 32 bits: ");
BigInteger p = sc1.nextBigInteger();
while(p.isProbablePrime(1) == false && p.compareTo(BigInteger.valueOf(2147483647)) == 1);
{
System.out.print("Sorry your p value must be a prime and up to 32bits! Please enter again: ");
p = sc1.nextBigInteger();
}

所以我输入了一个大于2147483647的值,我的while第一次工作,但第二次不运行。

Enter prime p value up to 32 bits: 2147483659
Sorry your p value must be a prime and up to 32bits! Please enter again: 2147483659
Enter prime q value up to 32 bits:

当我的条件没有得到满足时,它会跳到我的q值。

尝试使用以下代码(例如,去掉do/while(:

Scanner sc1 = new Scanner(System.in);
System.out.print("Enter prime p value up to 32 bits: ");
BigInteger p = sc1.nextBigInteger();
while(!p.isProbablePrime(1) || p.compareTo(BigInteger.valueOf(2147483647)) == 1) {
System.out.print("Sorry your p value must be a prime and up to 32bits! Please enter again: ");
p = sc1.nextBigInteger();
}

你能用这个吗?

public static void main(String[] args) {
Scanner sc1 = new Scanner(System.in);
System.out.print("Enter prime p value up to 32 bits: ");
BigInteger p = sc1.nextBigInteger();
while (!p.isProbablePrime(1) || p.compareTo(BigInteger.valueOf(2147483647)) > 0)) {
System.out.print("Sorry your p value must be a prime and up to 32bits! Please enter again: ");
sc1 = new Scanner(System.in);
p = sc1.nextBigInteger();
}
}

DO循环无论发生什么都将始终执行一次。所以你的coniditon总是计算为false(所以循环停止(。试着像这样设置

public final long c = 2147483647;
while(!p.isProbablePrime(1) || p.compareTo(BigInteger.valueOf(c)) == 1);

那是的

do{
//do stuff here
}while(condition to break the loop)     

最新更新