在方法中使用对象,Java
Using object in a method, Java
我不确定这里有什么问题,编程新手。我正在尝试访问 Combat
class 中的 hero1
对象,目前在 while 循环中它指出 hero1 无法解析为变量 .
我真的很想知道是否有任何方法可以在 Combat class 中访问对象 hero1 并且它是方法 combat。
快速说明一下,我有一个地精 class,它工作正常,这只是一个问题,因为我创建的对象与我所知道的不同 class。
感谢并为陈词滥调的 RPG 参考道歉。
Hero
class:
public class Hero {
String heroname;
double herohealth;
int heroattack;
String namehero() {
System.out.println("Please enter the Name of your Hero: ");
Scanner scan = new Scanner(System.in);
this.heroname = scan.nextLine();
return heroname;
}
}
Intro
class:
public class Intro {
public static void main(String args[]) {
Hero hero1 = new Hero();
hero1.heroattack = 15;
hero1.herohealth = 100;
hero1.namehero();
System.out.println("Welcome " + hero1.heroname + "!!!");
Combat fight = new Combat();
fight.combat();
}
}
Combat
class:
public class Combat {
public void combat() {
Goblin goblin1 = new Goblin();
while (hero1.herohealth > 0 || goblin1.goblinhealth > 0) {
System.out.println(hero1.heroname);
}
}
}
你的热情为我唱起小夜曲。当您按照其他人的建议在教程中取得进展时,请密切注意构造函数。
作为练习,您可能想制作一个 "Battle" 自己的 class。
在 Battle 的构造函数中,发送一个 Goblin
和你的 Hero
classes 作为参数。
然后,您可能有一个 method/function 叫做 fight()
Hero hero = new Hero();
hero.nameHero();
Goblin goblin1 = new Goblin();
Battle firstBattle = new Battle(hero, goblin1);
firstBattle.fight();
考虑一下您成为优秀程序员的另一个步骤(不一定是最好的步骤)(请原谅 rpg 参考 ;))
我不确定这里有什么问题,编程新手。我正在尝试访问 Combat
class 中的 hero1
对象,目前在 while 循环中它指出 hero1 无法解析为变量 .
我真的很想知道是否有任何方法可以在 Combat class 中访问对象 hero1 并且它是方法 combat。
快速说明一下,我有一个地精 class,它工作正常,这只是一个问题,因为我创建的对象与我所知道的不同 class。
感谢并为陈词滥调的 RPG 参考道歉。
Hero
class:
public class Hero {
String heroname;
double herohealth;
int heroattack;
String namehero() {
System.out.println("Please enter the Name of your Hero: ");
Scanner scan = new Scanner(System.in);
this.heroname = scan.nextLine();
return heroname;
}
}
Intro
class:
public class Intro {
public static void main(String args[]) {
Hero hero1 = new Hero();
hero1.heroattack = 15;
hero1.herohealth = 100;
hero1.namehero();
System.out.println("Welcome " + hero1.heroname + "!!!");
Combat fight = new Combat();
fight.combat();
}
}
Combat
class:
public class Combat {
public void combat() {
Goblin goblin1 = new Goblin();
while (hero1.herohealth > 0 || goblin1.goblinhealth > 0) {
System.out.println(hero1.heroname);
}
}
}
你的热情为我唱起小夜曲。当您按照其他人的建议在教程中取得进展时,请密切注意构造函数。
作为练习,您可能想制作一个 "Battle" 自己的 class。
在 Battle 的构造函数中,发送一个 Goblin
和你的 Hero
classes 作为参数。
然后,您可能有一个 method/function 叫做 fight()
Hero hero = new Hero();
hero.nameHero();
Goblin goblin1 = new Goblin();
Battle firstBattle = new Battle(hero, goblin1);
firstBattle.fight();
考虑一下您成为优秀程序员的另一个步骤(不一定是最好的步骤)(请原谅 rpg 参考 ;))