我知道sumOfMultiples方法本身的工作原理和問題在於主要方法。當我運行它時,沒有任何反應,它只是連續運行。我使用netbeans如果有所作爲。沒有得到輸出到我的程序,只是說「正在運行...」
package examp;
public class Main {
public static void main(String[] args) {
Main example = new Main();
System.out.println("The answer is " + example.sumOfMultiples(2, 3));
}
public int sumOfMultiples(int num1, int num2) {
int num1Total = 0;
int num2Total = 0;
//Total of the multiples of the first number.
while (num1 < 1000) {
num1Total = num1Total + num1;
num1 = num1 + num1;
}
//Total of the multiples of the second number.
while (num2 < 1000) {
if (num2 % num1 != 0) { //Makes sure it doesn't add multiples of the first number twice.
num2Total = num2Total + num2;
}
}
return num1Total + num2Total;
}
}
對不起,如果這是一個愚蠢的問題,只是在幾分鐘前做了一個帳戶。
爲什麼你不聲明方法是靜態的,並且在不初始化Main實例的情況下使用它? – CSCH