英文:
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;
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论