[英]Java - Why is this an infinite loop and how can I fix it?
這是我當前正在處理無限循環的地方的一小段代碼。 遇到此循環時,我已將所有變量設置為它們在程序中的值。 此循環的目標是使其中斷(當然不會使用這些值)或經歷整個循環然后繼續前進,我相信它應該基於for循環中設置的條件,而是變成無限循環。 我迷路了,想知道是否有人可以幫助我。 為什么這是一個無限循環,我該如何解決? 謝謝。
第一個代碼段是顯示無限循環的最小代碼。 我放置System.out.println(“ Infinite”);的地方; 是發生無限循環的地方。 它永遠不會到達for循環中的if語句。 我嘗試調試無濟於事。
int e = 1;
int f = 0;
int q = 2;
int posInt = 10;
int[] Prime = new int[posInt];
Prime[0] = 2;
Prime[1] = 3;
Prime[2] = 5;
int stay = 0;
while(stay == 0){
while(e <= posInt){
if((q + 1) == Prime[f]){
stay++;
System.out.println("BREAKING");
break;
}
e++;
f++;
}
q++;
}
到目前為止,這里是整個程序,以防萬一。 目的是通過使用Eratosthenes篩網測試用戶輸入的數字是否為質數。 我意識到程序中可能還存在其他錯誤,並且可能不正確,但是我仍在努力。 目前,我陷入了無限循環,因此無法繼續前進。
int posInt;
Scanner reader = new Scanner(System.in);
System.out.print("Please enter in any positive integer greater than one to see if it is a prime number: ");
posInt = reader.nextInt();
System.out.println();
int n = posInt;
int q = 2;
int a = 3;
int b = 1;
int[] list = new int[n];
list[0] = 2;
while(a <= n){
list[b] = a;
a++;
b++;
}
int c = 2;
int d = 0;
int P = 0;
int nP = 0;
int[] notPrime = new int[n];
int[] Prime = new int[n];
while(c <= n){
if(list[d] == q){
Prime[P] = list[d];
P++;
}
else if(list[d] % q == 0){
notPrime[nP] = list[d];
nP++;
}
else{
Prime[P] = list[d];
P++;
}
c++;
d++;
System.out.println("Primes numbers: ");
int y = 1;
int z = 0;
while(y <= P){
System.out.println(Prime[z]);
y++;
z++;
}
System.out.println("Numbers that are not prime: ");
y = 1;
z = 0;
while(y <= nP){
System.out.println(notPrime[z]);
y++;
z++;
}
int stay = 0;
int e = 1;
int f = 0;
while(stay == 0){
while(e <= posInt){
if(!((q + 1) == notPrime[f])){
stay++;
break;
}
e++;
f++;
}
q++;
}
}
int g = 2;
int h = 0;
boolean prime = false;
while(g <= n){
if(posInt == Prime[h]){
prime = true;
break;
}
g++;
h++;
}
if(prime = true){
System.out.println("The number " + n + " is prime.");
}
else if(prime = false){
System.out.println("The number " + n + " is not prime.");
}
reader.close();
無限循環不是在第一個片段,它的周圍while
-如果break
從未發生過, stay
也將總是0
,除非其他操作之一拋出,你會永遠存在被卡住的例外......
int stay = 0;
while(stay == 0){
int e;
int f = 0;
for(e = 1; e <= posInt; e++){
if((q + 1) == Prime[f]){
stay++;
break;
}
f++;
System.out.println("Infinite");
}
q++;
}
您需要一種方法來停止while循環。 因此,在循環外聲明int f並將其置於while條件中:
int stay = 0;
int f = 0;
while (f < posInt && stay == 0) {
int e;
for (e = 1; e <= posInt; e++) {
if ((q + 1) == Prime[f]) {
stay++;
break;
}
f++;
System.out.println("Infinite");
}
q++;
}
而且,您必須查看其余代碼中的邏輯(如您自己所述)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.