Java while循环非法启动类型问题
嘿,我得到一个错误,它统计了while循环开始时类型的非法开始:Java while循环非法启动类型问题,java,loops,while-loop,Java,Loops,While Loop,嘿,我得到一个错误,它统计了while循环开始时类型的非法开始: public class hello { public static void main (String [] arg) { int sum1=sum(7, 13); } public static int sum(int x, int y) { int z=0; } while (y > 0) { z = z + x;
public class hello {
public static void main (String [] arg) {
int sum1=sum(7, 13);
}
public static int sum(int x, int y) {
int z=0;
}
while (y > 0) {
z = z + x;
y--;
}
return (z)
}
}
在
int z=0
之后移除大括号,并在return(z)
之后添加分号
正如chenchuk所说,multiply
将是该方法的一个更正确的名称,因此我继续并更改了它。我在那里也提出了一个建议,在while
循环中的注释中
像这样:
public class Hello {
public static void main(String[] arg) {
int sum1 = multiply(7, 13);
}
public static int multiply(int x, int y) {
int z = 0;
while (y > 0) {
// You can say z += x; here, think of it as shorthand
z = z + x;
y--;
}
return z;
}
}
不能将
while
循环放在这样的方法体之外。养成正确缩进代码的习惯,这些类型的错误就更容易看到了正如Reimeus所提到的,适当地缩进代码,这样可以很容易地捕获这些错误。为了使您的生活更轻松,请使用IDE。Netbeans/Eclipse/…漂亮的缩进代码。。。您还可以将“hello”改为“hello”。我建议将方法名称从“sum”改为“multiply”