Java:我的错误是在线程的运行方法中出现了一个找不到符号的错误?

huangapple go评论85阅读模式
英文:

Java : My error is a cannot find symbol in run method for Threads?

问题

public class Battle extends Thread {

    private Instructor instructor1;
    private Instructor instructor2;

    public Battle(Instructor instructor1, Instructor instructor2) {
        this.instructor1 = instructor1;
        this.instructor2 = instructor2;
    }

    public void run() {
        while ((instructor1.getCurrentHP() > 0) || (instructor2.getCurrentHP() > 0)) { 
            System.out.print(2);
        }
    }

    public static void main(String[] args) {
        Instructor instructor1 = new Instructor("大奥马尔·拉蒂夫", 999, 145, 180, 4000);
        Instructor instructor2 = new Instructor("小阿里·拉扎", 400, 185, 230, 1200);
        Battle x = new Battle(instructor1, instructor2);

        x.start();
    }
}
英文:
public class Battle extends Thread{

   public Battle(Object instructor1, Object instructor2){
  
}

public void run(){

  while ((instructor1.getCurrentHP() > 0) || (instructor2.getCurrentHP() > 0)){ //ERROR HERE
     System.out.print(2);
  }

}

public static void main(String[] args){
   Instructor instructor1 = new Instructor("Big Omar Latif", 999, 145, 180, 4000);
   Instructor instructor2 = new Instructor("Small Ali Raza", 400, 185, 230, 1200);
   Battle x = new Battle(instructor1, instructor2);
  
   x.start();
  
} 


} 

'''
So heres my code. I have 2 instructors fighting each other and there will be mulitple rounds for them.
I want a battle(round) to be threaded.
Now when i run this, i get a symbol not found error for the while loop for the instructor1 and instructor2. Im assuming my understanding for the run() method isnt clear. Can you help me figure it out?

答案1

得分: 4

你必须将Object instructor1和Object instructor2声明为全局变量,并在构造函数中进行初始化,以便它们可以在不同的方法中访问。

public class Battle extends Thread{
    
    private Object instructor1;
    private Object instructor2;

    public Battle(Object instructor1, Object instructor2){
        this.instructor1 = instructor1;
        this.instructor2 = instructor2;
    }
}
英文:

You have to declare Object instructor1, Object instructor2 as a global variable and initialize them in constructor in order for them to access on different methods.

  public class Battle extends Thread{
    
    private Object instructor1;
    private Object instructor2;

      public Battle(Object instructor1, Object instructor2){
         this.instructor1=instructor1;
         this.instructor2=instructor2;
      }
}

huangapple
  • 本文由 发表于 2020年3月15日 16:48:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/60691136.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定