Java 如何从其他类中增加值(位于主类中)

Java 如何从其他类中增加值(位于主类中),java,class,variables,int,increment,Java,Class,Variables,Int,Increment,我想从另一个类向主类中的值添加一个,但错误一直指向“Balance” 这个错误发生在我的另一个类“RevenueThread”中,当时我说要获取这个类,然后变量再递增1 这是完整的代码 import java.util.*; public class Main{ public static void main (String [] args){ boolean running = true; boolean property1 = false; Scanner in

我想从另一个类向主类中的值添加一个,但错误一直指向“Balance”

这个错误发生在我的另一个类“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() );
            }
        }
    }


}

}

将其设置为您希望从另一个类访问的
类变量(在您的情况下为
余额

局部变量在声明它们的方法之外不可见

留着这根棍子

int Balance = 0;
在main方法之前,将其设置为静态。之后,您将能够像这样访问它

Main.Balance++;