当我已经声明了变量时,如何修复空错误



我正在制作一个PVP RPG游戏,显示框显示"null"而不是我已经声明的变量。

我已将该变量声明为用户的下一个输入,并将该信息存储在变量中。然后当我尝试显示变量时,它只显示"null",

System.out.println("Welcome, Player One and Player Two!");
delay(1500);
System.out.println("What is your name, Player One?");
playerOne.name = userInput.nextLine();

我已经将玩家一宣布为新角色(不同职业)

System.out.println("Your turn, " + playerOne.name+".");
if (p1Swordgo == 1) {

这就是我想出的问题。它在同一个主方法中,变量在主方法中声明,是的,我导入了扫描仪并声明了变量 userInput

我希望它是用户输入的内容,但它得出了 null。正如我之前所说,它在相同的主方法中,应该不会出错,但它会提出"null">

import java.util.Random;
import java.util.Scanner;

public class Arena {
Random generator = new Random();

public static void main(String[] args) {
Character playerOne = new Character(10,10,0);
Character playerTwo = new Character(10,10,0);
boolean P1hasClass = false;
boolean P2hasClass = false;
int p1Swordgo = 0;
int p2Alchgo = 0;
int p2Archgo = 0;

Scanner userInput = new Scanner(System.in);
System.out.println("Welcome, Player One and Player Two!");
delay(1500);
System.out.println("What is your name, Player One?");
playerOne.name = userInput.nextLine();
delay(1000);
System.out.println("Hello, " +playerOne.name +".");
delay(1000);
System.out.println("What is your name, Player Two?");
playerTwo.name = userInput.nextLine();
delay(1000);
System.out.println("Hello, " +playerTwo.name +".");
delay(1500);
countdown();
System.out.println("Your turn, " + playerOne.name+".");
if (p1Swordgo == 1) {
if (p2Archgo == 1 || p2Alchgo == 1) {
if (playerOne.move == 1){
System.out.println("What do you want to do?" +'n' +"1 = Move into range of " +playerTwo.name +'n' +"2 = Heal" +'n' +"3 = Forfeit");
int P1Choice = userInput.nextInt();
if (P1Choice == 1) {
playerOne.move --;
System.out.println(playerOne.move);
}
}

}
}


}








public static void delay ( int time){
try {
Thread.sleep(time);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
public static void countdown() {
delay(500);
System.out.println("Get ready to fight in 5,");
delay(1000);
System.out.println("4");
delay(1000);
System.out.println("3");
delay(1000);
System.out.println("2");
delay(1000);
System.out.println("1");
delay(1000);
System.out.println("Fight!");
delay(750);
}

}

然后在一个名为 Character 的类中

public class Character {

public int strength;
public double health;
public int move;
public String name;

public Character(double health, int strength, int move) {
this.health = health;
this.strength = strength;
this.name = name;
this.move = move;
}

}

在一个名为剑斗士的班级中

public class SwordFighter extends Character {
public SwordFighter() {
super(60,15, 1);
}

}

在一个叫弓箭手的班级里

public class Archer extends Character{
public Archer() {
super(45,20, 0);
}

}

最后,在一个叫做炼金术士的班级里 公共类炼金术士扩展角色{

public Alchemist() {
super(50,15, 0);
}

}

顺便说一下,感谢您的耐心等待

一旦两个玩家选择了他们的名字,并且你用playerOne.name = userInput.nextLine();设置了它,你分配一个不同的对象,一个空名称,playerOne

playerOne = new SwordFighter();

因此,在执行此行后,playerOne.name为 null。

相关内容

  • 没有找到相关文章