我的代码抛出NPE运行时错误[重复]

时间:2021-11-22 20:22:32

This question already has an answer here:

这个问题在这里已有答案:

I hope it isn't too much trouble if I just post all the code I have. If anyone would be willing to take a look at it, that would be awesome. Sorry that I'm kind of clueless.. :/ I tried the suggestions from the answers but to be honest, I don't think I did it right... so... maybe I'm just making a simple mistake.

如果我发布所有代码,我希望不是太麻烦。如果有人愿意看一眼,那就太棒了。对不起,我有点无能......:/我尝试了答案中的建议,但说实话,我认为我做得不对......所以...也许我只是犯了一个简单的错误。

    public class Enemy {

/**
 * This field 
 */
private Gun gun;

/**
 * This field holds the amount of hitpoints the enemy has, which is 5.
 */
private int hitPoints;

GameEngine ge = new GameEngine();

/**
 * This method determines whether the enemy shot hit or not.
 */
public boolean enemyShotSuccess(){
    return gun.shoot(ge.enemySpawn());
}

/**
 * This method determines what the enemy drops if it dies.
 */
public String Item_Drop(){
    Random rdm_Numbers = new Random();
    int Random_Item = rdm_Numbers.nextInt(100);
    String Dropped_Item = null;

    if (Random_Item >= 0 && Random_Item < 30)
        Dropped_Item = "Health";
    if (Random_Item >= 30 && Random_Item < 100)
        Dropped_Item = "Ammo";
    return Dropped_Item;

}

/**
 * This is the default constructor that holds the 5 hitpoints of the enemy, as well as the gun it spawns with.
 */
public Enemy(Gun chosenGun){
    gun = chosenGun;
    hitPoints = 5;  
}

/**
 * When the enemy is hit, this method updates the hit points.
 */
public int dmgTaken(int dmg){
    hitPoints -= dmg;
    return hitPoints;
}

/**
 * This is a getter for the remaining hp of the enemy.
 */
public int getHP(){
    return hitPoints;
}

/**
 * This method calls the Item_Drop method when the enemy dies.
 */
public boolean die(){
    this.Item_Drop();
    return true;
}
}

next class

    public class GameEngine {

/**
 * These are the 3 enemies that can appear, stored in variables.
 */
public static enum OPPONENT_LEVEL {THUG, SPECIALIST, BERSERKER};

private Player player;

private Enemy enemy;

/**
 * This method creates a new character and lets the player choose a gun.
 * @param playerGun
 * @param playerHP
 * @param enemyGun
 * @param enemyHP
 */
public Player NewGame(Gun playerGun){
    return player = new Player(playerGun);
}

/**
 * This method determines whether the player was successful in shooting or not.
 */
public boolean playerTurn(Gun playerGun){
    player.playerShotSuccess(playerGun);
    return player.playerShotSuccess(playerGun);
}

/**
 * This method holds the chance for the player to escape.
 */
public boolean attemptEscape(){
    Random random = new Random();
    boolean success;
    int escape = random.nextInt(100);

    if (escape < 10)
        success = true;
    else success = false;
    return success;         
}

/**
 * This method gets the amount of ammo left in the clip.
 * @return
 */
public int ammoRemaining(){
    return player.ammoRemaining();
}

/**
 * This method determines the type of enemy that spawns, and gives it its respective weapon.
 * @return
 */
public Gun enemySpawn(){

Random random = new Random();
OPPONENT_LEVEL ol = null;   
int enemySpawned = random.nextInt(100);
Gun enemyGun = null;

if (enemySpawned < 50){
    enemyGun = new Gun(75, 1, 15);
    Enemy enemy = new Enemy(enemyGun);
    OPPONENT_LEVEL enemyName = ol.THUG;
    System.out.println("A " + enemyName + " has spawned! He has a pistol and 5 hp.");
}
if (enemySpawned >= 50 && enemySpawned < 85){
    enemyGun = new Gun(65, 2, 10);
    Enemy enemy = new Enemy(enemyGun);
    OPPONENT_LEVEL enemyName = ol.SPECIALIST;
    System.out.println("A " + enemyName + " has spawned! He has a rifle and 5 hp.");
}   
if (enemySpawned >= 85 && enemySpawned < 100){
    enemyGun = new Gun(40, 5, 5);
    Enemy enemy = new Enemy(enemyGun);
    OPPONENT_LEVEL enemyName = ol.BERSERKER;
    System.out.println("A " + enemyName + " has spawned! He has a shotgun and 5 hp.");
}   
return enemyGun;
}

/**
 * This method holds the remaining hp of the enemy.
 * @return
 */
public int enemyRemainingHP(){
    return enemy.dmgTaken(enemy.getHP());
}
}

next class

    public class Gun {

/**
 * This method will return true if, when shot, the shot is a hit.
 * If it is a miss, it will return false.
 */
public boolean shoot(Gun playerGun){
    boolean hit = false;
    Random Random_Numbers = new Random();
    int chanceOfShooting = Random_Numbers.nextInt(100);

    if (chanceOfShooting < accuracy){
        hit = true;
    }   
    return hit;
    }   

/**
 * This field holds the the maximum amount of bullets one clip can hold.
 */
private int clipSize;

/**
 * This field holds the accuracy of the gun.
 */
private int accuracy;

/**
 * This field holds the damage of the gun.
 */
private int damage;

/**
 * This field holds the amount of remaining bullets in the clip.
 */
private int ammoRemaining;

 /**
  * This field gets the amount of bullets remaining in the clip.
  * @return
  */
public int getAmmoRemaining(){
     ammoRemaining = clipSize - 1;
     return ammoRemaining;
}

 /**
  * This is the default constructor for the Gun, holding accuracy, damage and size of the clip.
  */
public Gun(int gunAccuracy, int gunDMG, int clip){
    accuracy = gunAccuracy;
    damage = gunDMG;
    clipSize = clip;
}

/**
 * This method gets the damage of the gun.
 */
public int getDMG(){
    return damage;
}
}

next class

    public class Player {

private Gun gun;

/**
 * This method determines whether the player's shot was a hit or miss.
 */
public boolean playerShotSuccess(Gun playerGun){
    gun.shoot(playerGun);
    return gun.shoot(playerGun);
}

/**
 * This field holds the amount of hitpoints that the player spawns with.
 */
private int hitPoints;

/**
 * This is the default constructor which says that the player has 20 hitpoints, and 
 * also displays the player's gun choice.
 */
public Player(Gun chosenGun){
    hitPoints = 20;
    chosenGun = gun;
}
/**
 * This method updates the player's hp with the damage received by the enemy.
 */
public int dmgTaken(int dmg){
    hitPoints -= dmg;
    return hitPoints;
}

/**
 * This method gets the damage of the gun the player is currently using.
 * @return
 */
public int getDMG(){
    return gun.getDMG();
}

/**
 * This field updates the amount of ammo remaining whenever a shot is fired.
 * @return
 */
public int ammoRemaining(){
    return gun.getAmmoRemaining();
}

}

next class

public class UI {
public static void main(String[] args){
    UI ui = new UI();
    ui.startGame();
}

/**
 *This field is for user input
 */
private Scanner keyboard;

GameEngine ge = new GameEngine();


/**
 * This method executes the game by calling all the associated methods.
 */
public void startGame(){
    keyboard = new Scanner(System.in);
    welcomeMessage();

    Gun playerGun = weaponChoice(welcomeMessage());

    ge.NewGame(playerGun);
    takeStep(playerGun, ge.NewGame(playerGun));

    keyboard.nextLine();    
}

/**
 * This method prints the welcoming message to the player.
 */
public int welcomeMessage(){
    System.out.println("Welcome to escape the dungeon! You are 10 steps away from the exit.");
    System.out.println("Be wary of enemies! \nThe pistol has 15 bullets, 75% accuracy, and does one damage. "
            + "\nThe rifle has 10 bullets, 65% accuracy, and does 2 damage. "
            + "\nThe shotgun has 5 bullets, 40% accuracy, and does 5 damage.");
    System.out.println("Choose your weapon. \nPress 1 for pistol. "
            + "\nPress 2 for rifle. "
            + "\nPress 3 for shotgun.");

    Scanner keyboard = new Scanner(System.in);
    int weaponChoice = keyboard.nextInt();

    return weaponChoice;
}

/**
 * This method allows the player to choose his or her weapon.
 */
public Gun weaponChoice(int weaponChooser){

    Gun playerGun = new Gun(0, 0, 0);
    switch (weaponChooser){
    case 1:
        playerGun = new Gun(75, 1, 15);
        System.out.println("You have selected the pistol!");
        break;
    case 2: 
        playerGun = new Gun(65, 2, 10);
        System.out.println("You have selected the rifle!");
        break;
    case 3:
        playerGun = new Gun(40, 5, 5);
        System.out.println("You have selected the shotgun!");
        break;
    default:
        playerGun = new Gun(0, 0, 0);
    }
    System.out.println(playerGun);
    return playerGun;   
}
/**
 * This is the main loop of the game. The player advances by pressing enter and, if met with an enemy, engages or attemps an escape.
 * @return
 */
public void takeStep(Gun playerGun, Player player){
    for (int oneStep = 1; oneStep <= 10; oneStep++){
        randomEncounter();
        if (randomEncounter()){
            Gun enemyGun = ge.enemySpawn();

            System.out.println("Press 1 to attack. \nPress 2 to attempt an escape and move back one step.");

            do {
            int Decision = keyboard.nextInt();

            if (Decision ==1){
                ge.playerTurn(playerGun);
                System.out.println("You have " + ge.ammoRemaining() + " bullets left.");
            }
            if (Decision ==2){
                ge.attemptEscape();
                if (ge.attemptEscape()){
                    oneStep -= 2;
                    System.out.println("You have succesfully escaped! You have moved back one step.");
                }
                else System.out.println("Sorry, you failed to escape and lost your turn.");
            }
            } while (ge.enemyRemainingHP() > 0);
        }
        System.out.println("You have taken one step! Only " + (10 - oneStep) + " more to go!");
        keyboard.nextLine();
        System.out.println("Press enter to take another step.");            
        keyboard.nextLine();
    }   
}

/**
 * This method holds the random encounter. There is a 15% chance to encounter an enemy.
 */
public boolean randomEncounter(){
    Random random = new Random();

    int randomEncounter = random.nextInt(100);

    if (randomEncounter < 15)
    return true;
    else return false;
}
}

and those are all of them. I do have a main to run the program.

这些都是他们。我有一个主程序来运行该程序。

1 个解决方案

#1


The stacktrace tells that the NPE occurs in player.playerShotSuccess(playerGun) So, player is null. Debug to see if weaponChoice() is returning a valid Gun object. Put a logger/system.out after the Gun playerGun = weaponChoice() line to see the initialized Gun object.

堆栈跟踪告诉NPE发生在player.playerShotSuccess(playerGun)中,因此,播放器为空。调试以查看weaponChoice()是否返回有效的Gun对象。在Gun playerGun = weaponChoice()行之后放置一个logger / system.out来查看初始化的Gun对象。

#1


The stacktrace tells that the NPE occurs in player.playerShotSuccess(playerGun) So, player is null. Debug to see if weaponChoice() is returning a valid Gun object. Put a logger/system.out after the Gun playerGun = weaponChoice() line to see the initialized Gun object.

堆栈跟踪告诉NPE发生在player.playerShotSuccess(playerGun)中,因此,播放器为空。调试以查看weaponChoice()是否返回有效的Gun对象。在Gun playerGun = weaponChoice()行之后放置一个logger / system.out来查看初始化的Gun对象。