您好我正在尝试重置java
中的计数器,因为我需要打印出一个数字因子的数量和因子的总和。当我输入多个整数值时,这些计数器会不断加起来。在输入每个新整数后,java中有没有办法重置计数器?到目前为止,这是我的代码。
import java.util.Scanner;
public class FindFactors {
public static void main (String args[]) {
Scanner in = new Scanner(System.in);
int num, factorcounter = 0;
int sumfactors = 0;
System.out.print("Enter a positive integer.");
while(in.hasNextInt()) {
num = in.nextInt();
if(num > 0) {
for(int i = 1; i <= num; i++) {
if(num % i == 0) {
factorcounter++;
System.out.println(i + " is a factor of " + num);
sumfactors = sumfactors + i;
}
}
System.out.println("The number of factors: " + factorcounter);
if (sumfactors / 2 == num) {
System.out.println(num + " is a perfect number!");
}
}
else {
System.out.println("Invalid Input");
}
}
}
}
答案 0 :(得分:0)
您必须为变量指定零。
Scanner in = new Scanner(System.in);
int num,factorcounter = 0;
int sumfactors = 0;
System.out.print("Enter a positive integer.");
while(in.hasNextInt())
{
num = in.nextInt();
factorcounter = 0;
sumfactors = 0;
if(num > 0)
{
for(int i = 1; i <= num; i++)
{
if(num % i == 0)
{
factorcounter++;
System.out.println(i + " is a factor of " + num);
sumfactors = sumfactors + i;
}
}
System.out.println("The number of factors: " + factorcounter);
if (sumfactors/2 == num)
{
System.out.println(num + " is a perfect number!");
}
}
else
{
System.out.println("Invalid Input");
}
}