[英]Beginner Java program (calculating deficient, abundant, prime, and perfect numbers)
do
{
System.out.println("Enter either limit, abundant, deficient, perfect, or prime = value:");
condition = scan.next();
String equals = scan.next();
num = scan.next();
value=Integer.parseInt(num);
if (Type.isInteger(condition) || !Type.isInteger(num) || value<0)
System.out.println("Please enter in condition = value format");
else
break;
}while(stop);
System.out.println("N" + "\t" + "Abundant" + " " + "Deficient" + " " + "Perfect" + " " + "Prime");
sigma = 0; //sets sigma=0
n=1;
while (stop)
{
for (f = 1; f <= n/2; f++)
{
if (n % f == 0)
sigma = sigma + f;
}
System.out.print(n + "\t");
if (sigma>n)
acount++;
if (sigma == 1)
p++; //prime counter
if (sigma<n)
dcount++; //deficient counter
if (sigma == n)
pcount++; //perfect counter
System.out.print(acount + " " + "\t" + " " + dcount + "\t" + " " + pcount + "\t" + " " + p); //prints abundant column
System.out.println();
if (condition.equals("limit"))
{
if(n<value)
n++;
else
break;
}
if(condition.equals("abundant"))
{
if(acount<value)
n++;
else
break;
}
if (condition.equals("deficient"))
{
if (dcount<value)
n++;
else
break;
}
if (condition.equals("perfect"))
{
if (pcount<=value)
n++;
else
break;
}
if (condition.equals("prime"))
{
if (p<value)
n++;
else
break;
}
}
}
}
本質上,該代碼應該打印出5列:n,豐富,不足,完美和質數。 每行下面都有一列數字。 用戶應該以“條件=值”格式輸入規范。 因此,如果他們輸入limit = 10,那么它將打印10行。 並且,如果他們輸入rich = 10,那么它將繼續打印行,直到rich的值達到10。我遇到的問題是,當我輸入某些值並且不確定原因是什么時,我的程序將無限循環。 例如,如果我輸入deficient = 2可以正常工作,但是如果我輸入deficient = 10則它將開始無限循環。 但是,當我輸入perfect = 10時,它只會打印出1行。 就像我的書名中所說的那樣,我是一個初學者,我不知道是什么導致了錯誤。 有什么建議么?
嘗試在循環內部初始化sigma的值:
while (stop)
{
sigma = 0;
...
}
由於sigma永遠不會重置為零,因此每個數字只會保持增長。 因此,您將很快停止尋找不足的數字或完美的數字,並且一切都會變得很充實。 這就是為什么rich關鍵字有效,而不足的關鍵字無效的原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.