import java.util.Scanner;
public class test {
public static void main(String args[]){
int a = 1000;
while(a>0){
System.out.println("Question to prevent infinite while loop");
Scanner input = new Scanner (System.in);
int inzet = input.nextInt();
System.out.println(a);
test(a);
}
}
public static void test(int a){
System.out.println(a);
a = a + 100;
System.out.println(a);
}
}
我有一个问题。为什么int a
不更新?每次都会重置为1000。我不想那样。有人可以帮帮我吗?如果我运行该程序,我会得到以下结果:
Question to prevent infinite while loop
2
1000
1000
1100
Question to prevent infinite while loop
2
1000
1000
1100
Question to prevent infinite while loop
2
1000
1000
1100
我想获取此代码:
Question to prevent infinite while loop
2
1000
1000
1100
Question to prevent infinite while loop
2
1100
1100
1200
Question to prevent infinite while loop
2
1200
1200
1300
此外,这是我的第一篇文章。请给我一些反馈,告诉我下次如何更好地提出问题。
最佳答案
您的更新值仅在您的 test
方法中可见。您可以将 a
设为字段并结合删除当前声明(在 main
方法以及 test
参数中):
import java.util.Scanner;
public class test {
private static int a = 1000;
public static void main(String args[]) {
while (a > 0) {
System.out.println("Question to prevent infinite while loop");
Scanner input = new Scanner(System.in);
int inzet = input.nextInt();
System.out.println(a);
test();
}
}
public static void test() {
System.out.println(a);
a = a + 100;
System.out.println(a);
}
}
或者您可以从方法中返回更新后的值,并将返回值分配给 a
:
import java.util.Scanner;
public class test {
public static void main(String args[]) {
int a = 1000;
while (a > 0) {
System.out.println("Question to prevent infinite while loop");
Scanner input = new Scanner(System.in);
int inzet = input.nextInt();
System.out.println(a);
a = test(a);
}
}
public static int test(int a) {
System.out.println(a);
a = a + 100;
System.out.println(a);
return a;
}
}
关于Java int 不更新。它重置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29798072/