我想在另一个类的主类中添加一个但是错误一直指向" 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() );
}
}
}
}
}
答案 0 :(得分:2)
将您想要从其他类访问的$ bash functionsubshell.sh
before myfunlocal : toto : dog foo : 123
myfunlocal - toto : dog foo : 123
myfunlocal - toto : lizard foo : 456
after myfunlocal : toto : dog foo : 123
myfun - toto : dog foo : 123
myfun - toto : lizard foo : 456
after subshell myfun: toto : dog foo : 123
myfun - toto : dog foo : 123
myfun - toto : lizard foo : 456
after simple myfun : toto : lizard foo : 456
。(在您的情况下为class variable
)
局部变量在声明它们的方法之外是不可见的。
保持这种形态
Balance
在main方法之前并使其成为静态。之后您将能够像这样访问它
int Balance = 0;