![](/img/trans.png)
[英]How can I change the value of a static class variable from a method, then get it from an other method?
[英]how to change the value of a static variable from a static method of another class
嗨,大家好,我在第一堂課上得到了這個變量
public static double credit;
在第一堂課的構造函數中,我得到了
credit=0.0;
然后我得到了這個偵聽器代碼,該代碼在用戶添加資金后在圖形窗口上顯示了我的價值
Catalogo.addCredit(credit);
creditLabel.setText("Credito: " + getCredit()+"€");
使用這兩個靜態方法,用於返回值(在第一類中)
public static double getCredit() {
return credit; }
為了增加資金,我使用了另一類
public static void addCredit(double creditl) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String cred = JOptionPane.showInputDialog(frame, "Inserisci l'importo da aggiungere:");
if (cred == null) {
return; }
if ((cred.matches("[0-9]*\\.[0-9]+")) || (cred.matches("[0-9]+"))) { //checks if the string is a valid double value or an int value
double credits = (double) Double.parseDouble(cred); //conversion into double
if (credits >= 0.0) {
JOptionPane.showMessageDialog(frame, "Credito aggiornato con successo");
creditl = creditl + credits;} }
if (!(cred.matches("[0-9]+")) && !(cred.matches("[0-9]*\\.[0-9]+"))) { //checks if the user didn't insert a correct double or int
JOptionPane.showMessageDialog(frame, "Importo inserito errato");
addCredit(creditl); }
}
現在的問題是信用變量根本沒有增加,我也不知道為什么一切似乎都很好,或者我錯過了什么? 輸入表示滿意,這意味着它檢查了正確的值,然后說信用已更新,但是沒有更新,我不知道為什么會這樣
注意:我試圖使此變量成為非靜態var,並將所有方法重命名為非靜態,但似乎是同一回事,同樣的問題
您沒有在代碼中的任何地方設置credit
等級變量。 您還有一個名為creditl
局部變量,也許這是您輸入問題的一部分。
具體來說,這行可能是問題所在:
creditl = creditl + credits;
(無論如何,您都應該重新設計。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.