[英]Java int doesn't update. It resets
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
方法中可見。 您可以結合刪除當前聲明(在您的main
方法和test
參數中)創建a
字段:
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;
}
}
創建a
類屬性:
public class test {
static int a = 1000;
//...
}
在Java中, int是一個原始對象,因此,當您將其傳遞給測試函數時,實際上是傳遞了該int的副本。
如果要通過IntRef
傳遞,可以使用IntRef
。
兩個第一個答案都是正確的
在這里閱讀更多關於引用與值的信息(不是Java專用): 按引用傳遞與按值傳遞有什么區別?
這里專門針對Java: Java是“按引用傳遞”還是“按值傳遞”?
第二種解決方案(向您的類添加名為a的靜態變量)可能會有所不同。 由於您的示例非常簡單,因此它具有相同的輸出。 但是,當您將static修飾符放入變量時,它將在該類的所有實例之間共享 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.