[英]Public Variables Not Being Read When Running One Method From Another
這不是我的實際代碼,但它顯示了我想要做的事情。 為什么 Print 方法在另一種方法中運行時最終打印原始值而不是更新的值? 當我從 PSVM 運行它們時,它會像我預期的那樣打印數字 3。
public int testOne = 0;
public static void main(String[] args) {
Main tester = new Main();
tester.Increase();
}
public void Increase() {
Main tester = new Main();
testOne = 3;
tester.Print();
}
public void Print() {
System.out.println(testOne);
}
}
Output 似乎為 0,有人知道為什么會這樣嗎? 如果它是編譯器,則在 repl.it 中運行它。
public void Increase() {
Main tester = new Main(); // new instance Main1, testOne = 0
testOne = 3; // current instance Main0, testOne = 3
tester.Print(); // calling Main1.Print() prints 0
}
The testOne assignment you do is the one in the current class, but you're actually calling the Print() function from a completely new instance of the class you created in the local scope.
你想要做的是:
public void Increase() {
testOne = 3;
Print();
}
此 Print() 方法將從當前 class 上下文中調用。
您面臨的問題是 scope。 在這里閱讀它: https://www.geeksforgeeks.org/variable-scope-in-java/
您有兩個 class 實例,因此有兩個 testOne 變量,但您只打印其中一個
要么你需要設置實例變量
public static void main(String[] args) {
Main tester = new Main();
tester.Increase();
// tester.Print(); // would print 0
}
public void Increase() {
Main tester = new Main();
tester.testOne = 3;
tester.Print();
}
public void Print() {
System.out.println(testOne); // prints 3
}
或者根本不創建另一個實例
public static void main(String[] args) {
Main tester = new Main();
tester.Increase();
}
public void Increase() {
this.testOne = 3;
this.Print();
}
public void Print() {
System.out.println(testOne);
}
另一種方法是使用 Static。
public static int testOne = 0;
public static void main(String[] args) {
Main tester = new Main();
tester.Increase();
}
public void Increase() {
Main tester = new Main();
testOne = 3;
tester.Print();
}
public void Print() {
System.out.println(testOne);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.