我尝试分别使用for,while和do-while循环计算5 * 10 * 15 * ... 50。当我运行我的代码时,它显示错误的答案,等于0.我无法找到我的代码中的问题。有人可以帮我看看吗?非常感谢~~以下是我的代码:
public class Main {
public static void main(String[] args) {
ForMethod show1 = new ForMethod();
show1.computeForLoop();
System.out.println();
DWMethod show2 = new DWMethod();
show2.computeDWLoop();
System.out.println();
WhileMethod show3 = new WhileMethod();
show3.computeWhileLoop();
}
}
// For Loop
public class ForMethod {
long mul;
public void computeForLoop(){
System.out.println("Compute using For Loop : ");
for(int x = 1; x <= 10 ; x++){
if ( x < 10){
System.out.print(x*5 + " x ");
} else { System.out.print(x*5);}
mul *= x*5;
}
System.out.println("\nThe Product of Number = " + mul);
}
}
// While Loop Method
public class WhileMethod {
int x = 1 ;
long mul;
public void computeWhileLoop(){
System.out.println("Compute using While Loop : ");
while(x < 10){
System.out.print(x*5 + " x ");
x++;
if (x == 10){
System.out.print(x*5);
}
mul *= (x*5);
}
System.out.println();
System.out.println("The Product of Number = " + mul);
}
}
// Do-While Loop Method
public class DWMethod {
int x = 1;
long mul;
public void computeDWLoop(){
System.out.println("Compute using Do-While Loop : ");
do{
if (x < 10 ){
System.out.print(x*5 + " x ");
} else
if (x == 10){
System.out.print(x*5);
}
mul *= x;
x++;
} while (x <= 10);
System.out.println();
System.out.println("The Product of Number = " + mul);
}
}
答案 0 :(得分:1)
问题是您的mul
字段初始化为零。这意味着你总是乘以零。
答案 1 :(得分:1)
您应该初始化mul
。如果您未初始化mul
,则计算机会为其指定值0。
答案 2 :(得分:0)
您应该使用值1来初始化mul
答案 3 :(得分:0)
在我看来,最好的方法是将mul初始化为“5”,然后开始循环2!