2015-11-21 18 views
2

我想將一個值添加到另一個類的主類中但是錯誤一直指向「餘額」。我如何從不同的類中增加一個值(這是在主類中)

錯誤發生在我的其他類「RevenueThread」的時候,我曾經說過,以獲取類,然後變量再經1

增加下面是完整的代碼

import java.util.*; 
public class Main{ 

public static void main (String [] args){ 

    boolean running = true; 
    boolean property1 = false; 

    Scanner in = new Scanner(System.in); 

    int Balance = 0; 

    String option = ""; 



    Load: 
    while(running){ 

     System.out.println("Choose an option"); 
     if(property1 == true){ 
      Runnable rev = new RevenueThread(); 
      Thread revThread = new Thread(rev); 
      revThread.start(); 
     } 
     System.out.println("Option 1: Buy Property"); 
     System.out.println("Option 2: Check balance"); 
     System.out.println(); 
     option = in.next(); 


     switch(option){ 

      case "1": 
       System.out.println("Do you want to buy a property?: "); 
       String ans = in.next(); 
       ans = ans.toUpperCase(); 
       if(ans.equals("Y")){ 
        property1 ^= true; 
        continue Load; 
       } 
       else if(ans.equals("N")){ 
        System.out.println("Property not bought come again soon!"); 
        continue Load; 
       } 
       else{ 
        System.out.println("Not recognised!"); 
        continue Load; 
       } 
       break; 

      case "2": 
       System.out.println("Your balance is: " + balance); 
       continue Load; 
       break; 
      default: 
     } 
    } 
} 
public static class RevenueThread implements Runnable { 

    public void run(){ 
     while(true){ 


      Main.Balance++; 

      try{ 
      Thread.sleep(1000); 
      }catch(Exception ex){ 
      System.err.println(ex.getMessage()); 
      } 
     } 
    } 


} 

}

回答

2

讓它class variable你想從另一個類訪問(在你的情況下Balance

局部變量是否在宣佈它們的方法之外可見。

保持這種statament

int Balance = 0; 

之前主要方法,並使其static.After,你將能夠訪問它像這樣

Main.Balance++; 
相關問題