[英]What is wrong in declaring data type of variable inside while loop but not inside for loop?
如果我声明变量然后在 while 循环中初始化变量,则没有问题。
int a;
while((a=someValue)!= -1)`
但是如果我声明变量并在while循环中初始化它,编译时就会出现问题。
while ((int a=someValue) != -1)
这是什么原因? 不过,在 For 循环中声明和初始化变量似乎没问题。
int a;
while ((a=Integer.parseInt(reader.nextLine())) != -1) {
sum.addNumber(a);
}
System.out.println("sum: "+sum.sum());
while ((int a=Integer.parseInt(reader.nextLine())) != -1) {
sum.addNumber(a);
}
System.out.println("sum: "+sum.sum());
因为你只能在while
循环的括号内写一个表达式。 从语义上讲,这是有道理的:假设您在while()
声明了一个变量,那么在每次迭代时它都会创建一个新的局部变量,并且您不能多次声明局部变量。
第二个已经给出了语法错误。 与For循环不同,您不能在While循环中声明变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.