Persistent java.lang.NullPointerException error from String.isEmpty() - java

I've been trying to search for the bug, but I couldn't find it. Already spent an hour trying to resolve what's wrong. The error begins when the code enters the isPlayerSet method while (!player.isPlayerSet()) {. I already set the used properties to "" but I am still getting this nullpointerexeption error. Please understand that I am fairly new in programming, especially in Java.
Here's the main class
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String playerName = "";
int chosenPokemon = 0;
boolean isANumber = false;;
Player player;
/*
* Initialize Players
*/
Player[] players = new Player[2];
for (int counter = 0; counter < players.length; counter++) {
player = new Player();
}
/*
* Get details of trainers
*/
for (int counter = 0; counter <= players.length-1; counter++) {
player = players[counter];
while (!player.isPlayerSet()) {
/*
* Input player name
*/
if(player.getPlayerName() == "") {
System.out.println("Enter a valid name for Player " + (counter+1) + ":");
player.setPlayerName(playerName);
}
/*
* Choose Pokemon
*/
if(player.getChosenPokemon() == ""){
System.out.println("Choose a starting pokemon for Player " + (counter+1) + ":");
System.out.println("[1] Charmander");
System.out.println("[2] Bulbasaur");
System.out.println("[3] Squirtle");
do {
if(!scanner.hasNextInt())
{
System.out.println("Input must be a valid integer. Try Again.");
scanner.next();
}
else if(!(chosenPokemon >= 1) && !(chosenPokemon <= 3))
{
System.out.println("Input must be a number from 1-3. Try Again.");
scanner.next();
}
else {
chosenPokemon = scanner.nextInt();
isANumber = true;
}
} while(!isANumber);
player.setChosenPokemon(chosenPokemon);
}
} // End of while loop
} // End of for loop
}
}
And here's the player class
public class Player {
Scanner scanner = new Scanner(System.in);
private String playerName = "";
private String chosenPokemon = "";
public String getPlayerName() {
return this.playerName;
}
public void setPlayerName(String playerName) {
do {
playerName = scanner.nextLine();
if(!isAlpha(playerName)) {
System.out.println("Invalid input. Try again");
}
if(playerName.isEmpty()) {
System.out.println("Player name cannot be blank! Try again");
}
} while(!isAlpha(playerName) || playerName.isEmpty());
this.playerName = playerName;
System.out.println("Welcome " + this.playerName);
}
public String getChosenPokemon() {
return chosenPokemon;
}
public void setChosenPokemon(int chosenPokemon) {
if(chosenPokemon == 1) {
this.chosenPokemon = "Charmander";
} else if(chosenPokemon == 2) {
this.chosenPokemon = "Bulbasaur";
} else {
this.chosenPokemon = "Squirtle";
}
}
public boolean isPlayerSet() {
if (this.playerName.isEmpty() && this.chosenPokemon.isEmpty()) {
return false;
}
return true;
}
public static boolean isAlpha(String name) {
char[] chars = name.toCharArray();
for (char c : chars) {
if (!Character.isLetter(c)) {
return false;
}
}
return true;
}
}
I also have another question, is it advisable to replace players[counter] with Player player?

You are creating new Player objects here:
for (int counter = 0; counter < players.length; counter++) {
player = new Player();
}
But: you are not storing those players in the array that you defined above. Thus: the array elements stay at its initial value - meaning that all players in the player array ... are null.
So your loop should say
players[counter] = new Player();
And of course, you really want to read this here.

In the loop
for (int counter = 0; counter < players.length; counter++) {
player = new Player();
}
You initialize the local variable player, so in while (!player.isPlayerSet()) player is null. You need to initialize the instance in the players array
for (int counter = 0; counter < players.length; counter++) {
players[counter] = new Player();
}

You're clobbering the same variable within this loop.
for (int counter = 0; counter < players.length; counter++) {
player = new Player();
}
Option 1:
for (int counter = 0; counter < players.length; counter++) {
players[counter] = new Player();
}
Option 2 (Slightly more concise and elegant):
for (Player p: players) p = new Player();

This
for (int counter = 0; counter < players.length; counter++) {
player = new Player();
}
should be this.
for (int counter = 0; counter < players.length; counter++) {
players[counter] = new Player();
}

Related

ArrayList of ArrayLists is overridden when setting values of a second one

I'm trying to make a battleship game, and this is the part where the players set their boards. When the second player to set the board makes theirs, the first player's board becomes the same as the second player's (when playing the game guessing the locations of that board are misses though, but that's another problem that will hopefully be fixed once this is). For example if I set the first player's ships as being at A1 A2 A3, B1 B2 B3, and C1 C2 C3, then set the second player's ships as D1 D2 D3, E1 E2 E3, and F1 F2 F3, when both lists of ships are printed out I get D1 D2 D3, E1 E2 E3, and F1 F2 F3 for both ships. I've found other questions on here with the same problem, but they always had the problem because they didn't make new lists every time, which I do (at least I'm pretty sure I do), so I can't find where my problem is. Here is the entire main game class, the GetShipLocations, SetShipLocations, and PlayersMakeTheirBoards, functions are what are giving me problems.
import java.util.*;
import java.lang.*;
public class MainGame {
InputReader read = new InputReader();
Grid p1Board = new Grid();
Grid p2Board = new Grid();
Grid p1ShipsBoard = new Grid();
Grid p2ShipsBoard = new Grid();
ArrayList<Ship> p1Ships = new ArrayList<Ship>();
ArrayList<Ship> p2Ships = new ArrayList<Ship>();
String activePlayer = "P1";
public void SetUp() {
p1Board.PrepPrintGrid();
p2Board.PrepPrintGrid();
Ship ship1 = new Ship();
Ship ship2 = new Ship();
Ship ship3 = new Ship();
p1Ships.add(ship1);
p1Ships.add(ship2);
p1Ships.add(ship3);
p2Ships.add(ship1);
p2Ships.add(ship2);
p2Ships.add(ship3);
}
public void GameIntro() {
System.out.println("Welcome to battleship!");
String rulesOption = read.getUserInput("Do you need to see the rules?");
if(rulesOption.equals("Yes") || rulesOption.equals("yes"))
{
System.out.println("Put rules here");
}
System.out.println("Randomly determining which player goes first");
int random = (int) (Math.random() * 2);
if(random == 1)
{
activePlayer = "P2";
}
System.out.println(activePlayer + " starts!");
}
public ArrayList<ArrayList<String>> GetShipLocations(Grid board) {
ArrayList<ArrayList<String>> ships = new ArrayList<ArrayList<String>>();
ArrayList<String> ship1 = new ArrayList<String>();
ArrayList<String> ship2 = new ArrayList<String>();
ArrayList<String> ship3 = new ArrayList<String>();
ships.add(ship1);
ships.add(ship2);
ships.add(ship3);
String[] numbers = {"first", "second", "third"};
board.PrepPrintGrid();
board.PrintGrid();
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
{
String coordinate = read.getUserInput("Enter the " + numbers[j] + " coordinate of your " + numbers[i] + " ship (3 long):");
ships.get(i).add(coordinate);
board.SetGridDisplay(coordinate, "hit");
board.PrintGrid();
}
}
return ships;
}
public void SetShipLocations(ArrayList<Ship> ship, Grid activeBoard) {
ArrayList<ArrayList<String>> shipLocations = GetShipLocations(activeBoard);
for(int i = 0; i < 3; i++) {
ship.get(i).SetCells(shipLocations.get(i));
}
}
public void PlayersMakeTheirBoards() {
if(activePlayer.equals("P1"))
{
System.out.println("Hand the computer to player one.");
System.out.println("Player one, time to set your board.");
SetShipLocations(p1Ships, p1ShipsBoard);//the effects of this seem to maybe be overriden when the second board is set
for(int i = 0; i < /*100*/3; i++)
{
for(int j = 0; j < 3; j++)
{
System.out.println(p1Ships.get(i).cells.get(j));
}
}
System.out.println("Hand the computer to player two.");
System.out.println("Player two, time to set your board.");
SetShipLocations(p2Ships, p2ShipsBoard);
for(int i = 0; i < /*100*/3; i++)
{
for(int j = 0; j < 3; j++)
{
System.out.println(p2Ships.get(i).cells.get(j));
}
}
for(int i = 0; i < /*100*/3; i++)
{
for(int j = 0; j < 3; j++)
{
System.out.println(p1Ships.get(i).cells.get(j));
}
}
}
else
{
System.out.println("Hand the computer to player two.");
System.out.println("Player two, time to set your board.");
SetShipLocations(p2Ships, p2ShipsBoard);
/*for(int i = 0; i < 100; i++)
{
System.out.println("");
}*/
for(int i = 0; i < /*100*/3; i++)
{
for(int j = 0; j < 3; j++)
{
System.out.println(p2Ships.get(i).cells.get(j));
}
}
System.out.println("Hand the computer to player one.");
System.out.println("Player one, time to set your board.");
SetShipLocations(p1Ships, p1ShipsBoard);
for(int i = 0; i < /*100*/3; i++)
{
for(int j = 0; j < 3; j++)
{
System.out.println(p1Ships.get(i).cells.get(j));
}
}
for(int i = 0; i < /*100*/3; i++)
{
for(int j = 0; j < 3; j++)
{
System.out.println(p2Ships.get(i).cells.get(j));
}
}
}
}
public void PlayTheGame() {
String guess = new String();
String result = new String();
for(int i = 0; i < 100; i++)
{
System.out.println("");
}
while(!p1Ships.isEmpty() && !p2Ships.isEmpty())
{
if(activePlayer.equals("P1"))
{
//print the grid
p1Board.PrintGrid();
//ask user for their guess
guess = read.getUserInput("Player one, enter your guess:");
for(Ship boat:p2Ships)
{
result = boat.CheckYourself(guess);
if(result.equals("hit"))
{
System.out.println(result + "!");
break;
}
if(result.equals("kill"))
{
System.out.println(result + "!");
p2Ships.remove(boat);
break;
}
}
if(result.equals("miss"))
{
System.out.println(result);
}
p1Board.SetGridDisplay(guess, result);
activePlayer = "P2";
}
else
{
p2Board.PrintGrid();
//ask user for their guess
guess = read.getUserInput("Player two, enter your guess:");
for(Ship boat:p1Ships)
{
result = boat.CheckYourself(guess);
if(result.equals("hit"))
{
System.out.println(result + "!");
break;
}
if(result.equals("kill"))
{
System.out.println(result + "!");
p1Ships.remove(boat);
break;
}
}
if(result.equals("miss"))
{
System.out.println(result);
}
p2Board.SetGridDisplay(guess, result);
activePlayer = "P1";
}
}
}
public void EndTheGame() {
String winner = new String();
if(p1Ships.isEmpty())
{
winner = "Player two";
p2Board.PrintGrid();
}
else
{
winner = "Player one";
p1Board.PrintGrid();
}
System.out.println("The game is over!");
System.out.println(winner + " wins! Congratulations!");
}
public static void main(String[] args) {
MainGame game = new MainGame();
game.SetUp();
game.GameIntro();
game.PlayersMakeTheirBoards();
game.PlayTheGame();
game.EndTheGame();
}
}
and here is the Ship class
import java.util.*;
public class Ship {
ArrayList<String> cells = new ArrayList<String>();
//String name = new String();
public void SetCells(ArrayList<String> locations) {
cells = locations;
}
/*public void SetName(String word) {
name = word;
}*/
public String CheckYourself(String guess) {
if(cells.contains(guess))
{
cells.remove(guess);
if(cells.isEmpty())
{
return "kill";
}
else
{
return "hit";
}
}
return "miss";
}
}
The grid and reader classes are working perfectly so I didn't include them.
(This is all based off the dotcom battleship game in headfirst java)
In your setup function:
public void SetUp() {
p1Board.PrepPrintGrid();
p2Board.PrepPrintGrid();
Ship ship1 = new Ship();
Ship ship2 = new Ship();
Ship ship3 = new Ship();
p1Ships.add(ship1);
p1Ships.add(ship2);
p1Ships.add(ship3);
p2Ships.add(ship1);
p2Ships.add(ship2);
p2Ships.add(ship3);
}
You are adding the same instances of ship1-3 to both p1Ships and p2Ships. So when you change the ships of player 2, the p1Ships ArrayList is still pointing to the same ships as p2Ships, and thus will always be the same.

Java - How To Compare Elements In An Object List

I am trying to get and compare average scores of a Player object stored in a List, where every object has a first name, last name, and a list of scores. An example of this would be (List with one object):
[0] Firstname: "Michael", Lastname: "Morris", Scores: [88, 92]
I have code with a nested for loop within a for loop that gives me an OutOfBounds error. I need to get the average of scores per Player and return the highest Player with the highest average. Here's what I have at the moment (The naming is kind off):
public static PlayerScores findHighestScorer(List<PlayerScores> players) {
String team = players.toString();
PlayerScores thePlayers = new PlayerScores("", ""); // What to return
for (int i = 0; i < team.length() - 1; ++i) { // Get every player and their average score
PlayerScores player = players.get(i); // First player
int avg = player.getAverage();
for (int j = i + 1; j < team.length(); ++j) {
PlayerScores player2 = players.get(j); // FIXME: OutOfBoundsException Error
int avg2 = player2.getAverage();
if (avg2 < avg) {
thePlayers = player;
} else if (avg2 > avg) {
thePlayers = player2;
} else {
thePlayers = player;
}
}
}
return thePlayers;
Any and all suggestions would be very helpful, thank you!
I hope this solves your problem! Cheers.
public static PlayerScores findHighestScorer(List<PlayerScores> players) {
PlayerScores bestScore = null;
// loop through list...
for (PlayerScores score : players) {
if (bestScore == null) {
bestScore = score;
} else {
if (bestScore.getAverage() < score.getAverage()) {
bestScore = score;
}
}
}
return bestScore;
}

Duplicate local variable for naming thread

Because I have a thread and in my main program I want to create multiple threads of the same thing and I don't want the same name I tried to create unique names for each thread, e.g Player_1, Player_2, etc.
The thing is that it throws Duplicate local variable which I know that is because I use the same variable but I don't know how else I can create multiple names for a thread without me writing them. Here is the code.
Original Question
for (int l=0; l < noPlayers; l++){
String name = P + "" + (l + 1);
System.out.println(name);
Player name = new Player(TURN);
}
*The Player is the thread which extends and TURN is just a variable that will be processed.
Updated Question
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.Scanner;
class Referee extends Thread{
}
class Player extends Thread{
private int TURN;
public Player(int TURN) {
this.TURN = TURN;
}
public void run(){
int win = 0;
int lose = 0;
int draw = 0;
boolean k = true;
int j = 0;
for (j=0;j<=TURN;j++){
String [] arr = {"ROCK", "PAPER", "SCISSORS"};
Random Pick = new Random();
// randomly selects an index from the arr
int select = Pick.nextInt(arr.length);
// prints out the value at the randomly selected index
System.out.println("Random String selected: " + arr[select]);
}
}
}
public class MainApp {
public static void main(String[] args) {
int TURN = 0;
int No_Players = 0;
int i=0;
boolean h= true;
int j=0;
boolean k = true;
System.out.println("Welcome to Rock-paper-scissors, this is a tutorial of threads");
Scanner number = new Scanner( System.in );
System.out.println("Insert the number of players that will play");
while (h){
while (!number.hasNextInt()){
System.out.println("You didnt insert a number please try again");
number.next();
}
if(number.hasNextInt()){
j = number.nextInt();
if(j>1){
No_Players = j;
h=false;
}
else {
System.out.println("You need a value bigger than 1");
}
}
}
System.out.println("Please enter how many turns you want each player to play");
while (k){
while (!number.hasNextInt()){
System.out.println("You didnt insert a number please try again");
number.next();
}
if(number.hasNextInt()){
i = number.nextInt();
if(i>0){
TURN = i;
k=false;
}
else {
System.out.println("You need a value bigger than 0");
}
}
}
System.out.println("This game will have " + No_Players +" players and each one will have " + TURN + " turns");
Map<String,Thread> map = new HashMap<>();
for (int l = 0; i < No_Players; ++i) {
String name = "Player_" + i;
Player player = new Player(TURN);
player.setName(name);
map.put(name, player);
player.start();
}
}
}
**Posted the whole code because of some misunderstandings.
Assuming that Player implements Runnable.
Map<String,Thread> map = new HashMap<>();
for (int i = 0; i < numPlayers; ++i) {
String name = "Player_" + i;
Player player = new Player(TURN);
Thread t = new Thread(player):
t.setName(name);
map.put(name, t);
t.start();
}
You can then retrieve the thread by the player name. You can also add a thread group if desired.
Based upon a comment that Player extends Thread (edit: fixed the Map definition to use Player rather than Thread).
Map<String,Player> map = new HashMap<>();
for (int i = 0; i < numPlayers; ++i) {
String name = "Player_" + i;
Player player = new Player(TURN);
player.setName(name);
map.put(name, player);
// thread may need to be started elsewhere depending upon the requirement
player.start();
}
Elsewhere to get the particular Player, just do:
Player p = map.get(playerName);
Based upon a comment, here is working example that show Player, extending Thread, using the Map suggested above, and displaying the players using the .getName() method on a Player object.
public class TestPlayer
{
public TestPlayer()
{
}
public static void main(String[] args)
{
int numPlayers = 5;
Map<String,Player> map = new HashMap<>();
for (int i = 0; i < numPlayers; ++i) {
String name = "Player_" + i;
Player player = new Player(0);
player.setName(name);
map.put(name, player);
// thread may need to be started elsewhere depending upon the requirement
player.start();
}
for (Player p : map.values()) {
System.out.println("Found player : " + p.getName());
}
}
static class Player extends Thread
{
private int turn;
public Player(int turn)
{
this.turn = turn;
}
#Override
public void run()
{
System.out.println("Running player " +
Thread.currentThread().getName() +
" turn " + this.turn);
}
}
}
Output:
Running player Player_1 turn 0
Running player Player_3 turn 0
Running player Player_0 turn 0
Running player Player_2 turn 0
Running player Player_4 turn 0
Found player : Player_3
Found player : Player_2
Found player : Player_4
Found player : Player_1
Found player : Player_0

How do I debug a NullPointerException? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I am trying to place ships on a console based board game, I have the following errors and not sure how to debug them.
Exception in thread "main" java.lang.NullPointerException
at NavalBattle.Board.print(Board.java:570)
at NavalBattle.Board.placeShipsP1(Board.java:267)
at NavalBattle.Board.(Board.java:61)
at NavalBattle.Controller.start(Controller.java:29)
at NavalBattle.Controller.main(Controller.java:21)
line 570 is value = this.ships2[row][col].toString();
import java.util.Scanner;
public class Controller {
/**
* The board that represents the current state of the game.
*/
private Board board;
public Controller() {}
/**
* This creates one Library object and calls its start method.
*
* #Param args
*/
public static void main(String[] args) {
new Controller().start();
}
int PL;
/**
* The PLrimary method that starts and coordinates a game. Call this to
* begin a new game.
*/
public void start() {
this.board = new Board();
Scanner scanner = new Scanner(System.in);
this.board.moveShip();
while (!this.board.isGameOver()) {
PL = 1;
this.board.moveShip();
PL = 2;
this.board.moveShip2(null);
this.board.remap();
this.board.moveShip2(null);
System.out.println("Enter a row and column number at which to shoot (e.g., 2,3): ");
String[] coordinates = scanner.nextLine().split(",");
if (coordinates.length != 2) {
System.out.println("PLlease enter coordinates in the correct format.");
continue;
}
int row = Integer.parseInt(coordinates[0].trim());
int column = Integer.parseInt(coordinates[1].trim());
this.board.bombOp(row, column);
}
if (PL == 1);{
System.out.println("Game Over Player 2 wins");
}
if (PL == 2){
System.out.println("Game Over Player 1 wins");
}
}
}
// Board Class
import java.util.ArrayList;
import java.util.Scanner;
public class Board {
int x = 0;
int y = 0;
ArrayList<Ships> player1 = new ArrayList<>();
ArrayList<Ships> player2 = new ArrayList<>();
/**
* The number of shots that have hit ships
*/
private int hitCount;
/**
* Track the locations of the board that have been fired upon
*/
private boolean[][] locationsFiredUpon;
/**
* Track the ships in the game
*/
private Ships[][] ships;
private Ships[][] ships2;
private Ships[][] shipsM;
/**
* The number of ships sunk
*/
private int shipsSunk;
/**
* The number of shots fired
*/
private int shotsFired;
/**
* Constructor. Initializes internal counters and populates the game
* board with randomly placed ships.
*/
public Board() {
this.hitCount = 0;
this.shipsSunk = 0;
this.shotsFired = 0;
board();
this.ships = new Ships[6][9];
this.ships2 = new Ships[6][9];
this.locationsFiredUpon = new boolean[6][9];
for (int row=0; row < this.ships.length; row++) {
for (int col=0; col < this.ships[row].length; col++) {
this.ships[row][col] = new Conflict();
this.locationsFiredUpon[row][col] = false;
}
}
this.placeShipsP1();
this.placeShipsP2();
this.moveShip();
this.moveShip2(player1);
}
public void remap() {
board();
this.locationsFiredUpon = new boolean[6][9];
for (int row=0; row < this.ships.length; row++) {
for (int col=0; col < this.ships[row].length; col++) {
this.ships[row][col] = new Conflict();
this.locationsFiredUpon[row][col] = false;
}
}
}
/**
* Constructor for testing. Accepts an input ship array and does not
* attempt to place ships
* #param shipArray
*/
public Board(Ships[][] shipArray) {
this.hitCount = 0;
this.shipsSunk = 0;
this.shotsFired = 0;
this.ships = shipArray;
this.locationsFiredUpon = new boolean[6][9];
for (int row=0; row < this.ships.length; row++) {
for (int col=0; col < this.ships[row].length; col++) {
this.locationsFiredUpon[row][col] = false;
}
}
}
public void board(){
this.ships = new Ships[6][9];
this.ships2 = new Ships[6][9];
}
/**
* Get the number of shots fired that have hit a ship.
* #return The number of shots fired that have hit a ship
*/
public int getHitCount() {
return this.hitCount;
}
/**
* Get the game board.
* #return A 2-D array of Ships representing the game
*/
public Ships[][] getShipArray() {
return this.ships;
}
public Ships[][] getShipArray2() {
return this.ships2;
}
/**
* Get the number of ships sunk.
* #return The number of ships sunk
*/
public int getShipsSunk() {
return this.shipsSunk;
}
/**
* Get the number of shots fired so far.
* #return The number of shots fired
*/
public int getShotsFired() {
return this.shotsFired;
}
/**
* Create an list of ships that can be placed on the board:
* - 1 battleship
* - 2 cruisers
* - 3 destroyers
* - 4 submarines
* #return ships to be placed on the board
*/
private ArrayList<Ships> generateInitialShipArrayList1() {
ArrayList<Ships> ship = new ArrayList<Ships>();
for (int i=0; i<1; i++) {
ship.add(new Battleship());
}
for (int i=0; i<0; i++) {
ship.add(new Minesweeper());
}
for (int i=0; i<0; i++) {
ship.add(new Destroyer());
}
for (int i=0; i<0; i++) {
ship.add(new Submarine());
}
for (int i=0; i<0; i++) {
ship.add(new Mines());
}
return ship;
}
private ArrayList<Ships> generateInitialShipArrayList2() {
ArrayList<Ships> ship2 = new ArrayList<Ships>();
for (int i=1; i<2; i++) {
ship2.add(new Battleship());
}
for (int i=1; i<1; i++) {
ship2.add(new Minesweeper());
}
for (int i=1; i<1; i++) {
ship2.add(new Destroyer());
}
for (int i=1; i<1; i++) {
ship2.add(new Submarine());
}
for (int i=1; i<1; i++) {
ship2.add(new Mines());
}
return ship2;
}
/**
* Indicate whether the game is over by checking if all ships have been
* sunk.
* #return true if all ships are sunk; otherwise false
*/
public boolean isGameOver() {
return (this.shipsSunk == 1);
}
/**
* Whether the specified position is occupied by a ship and is not empty
* sea.
* #param row
* #param column
* #return true if the position has a ship; else false
*/
public boolean isOccupied(int row, int column) {
System.out.println("Occupardo, you no go here");
return !(this.ships[row][column] instanceof Conflict);
}
public void placeShipsP1() {
System.out.println("");
print();
ArrayList<Ships> shipsToMove = this.generateInitialShipArrayList1();
player1 = this.generateInitialShipArrayList1();
boolean okToPlaceShipHere = false;
int row = 0;
int column = 0;
String Tp = "1";
boolean horizontal = false;
if(okToPlaceShipHere = false){
System.out.println("Occupardo, you no go here");
}
for (Ships ship : player1) {
while (!okToPlaceShipHere) {
Scanner scanner = new Scanner( System.in );
System.out.println("player1 enter a row and column (e.g., 2,3)");
System.out.println("please enter the row of " + ship.getShipType());
String[] coordinates = scanner.nextLine().split(",");
if (coordinates.length != 2) {
System.out.println("Please enter coordinates in the correct format.");
continue;
}
row = Integer.parseInt(coordinates[0].trim());
column = Integer.parseInt(coordinates[1].trim());
ship.setX(row);
ship.setY(column);
System.out.println(ship.getX() + " " + ship.getY());
// row = Random.nextInt(6);
// column = Random.nextInt(9);
horizontal = true;
okToPlaceShipHere = ship.okToPlaceShipAt(row, column, horizontal, this);
}
if( okToPlaceShipHere = true){
this.bombOp(row, column);
}
ship.setBowColumn(column);
ship.setBowRow(row);
ship.setPlayer(Tp);
ship.setX(row);
ship.setY(column);
System.out.println(ship.getX() + " " + ship.getY() + " " + ship.getPlayer());
ship.setHorizontal(horizontal);
this.placeShipIntoShipsArray(ship);
okToPlaceShipHere = false;
System.out.println("");
print();
}
}
public void placeShipsP2() {
System.out.println("");
print();
ArrayList<Ships> shipsToPlace = this.generateInitialShipArrayList1();
player2 = this.generateInitialShipArrayList2();
boolean okToPlaceShipHere = false;
int row = 0;
int column = 0;
String Tp = "2";
boolean horizontal = false;
if(okToPlaceShipHere = false){
System.out.println("Occupardo, you no go here");
}
for (Ships ship : player2) {
while (!okToPlaceShipHere) {
Scanner scanner = new Scanner( System.in );
System.out.println("Player 2 enter a row and column (e.g., 2,3)");
System.out.println("please enter the row of " + ship.getShipType());
String[] coordinates = scanner.nextLine().split(",");
if (coordinates.length != 2) {
System.out.println("Please enter coordinates in the correct format.");
continue;
}
row = Integer.parseInt(coordinates[0].trim());
column = Integer.parseInt(coordinates[1].trim());
ship.setX(row);
ship.setY(column);
System.out.println(ship.getX() + " " + ship.getY());
// row = random.nextInt(6);
// column = random.nextInt(9);
horizontal = true;
okToPlaceShipHere = ship.okToPlaceShipAt(row, column, horizontal, this);
}
ship.setBowColumn(column);
ship.setBowRow(row);
ship.setPlayer(Tp);
ship.setX(row);
ship.setY(column);
System.out.println(ship.getX() + " " + ship.getY() + " " + ship.getPlayer());
ship.setHorizontal(horizontal);
this.placeShipIntoShipsArray(ship);
okToPlaceShipHere = false;
System.out.println("");
print();
}
}
/**
* Place the given ship into locations in the
* 2Darray that tracks ship positions.
* #param ship
*/
private void placeShipIntoShipsArray(Ships ship) {
int row = ship.getBowRow();
int column = ship.getBowColumn();
// player1.add.ship;
player1.removeAll(player1);
player2.removeAll(player2);
if (ship.isHorizontal()) {
for (int i=0; i < ship.getLength(); i++) {
this.ships[row][(column+i)] = ship;
}
}
else {
for (int i=0; i < ship.getLength(); i++) {
this.ships[(row+i)][column] = ship;
}
}
}
public void ifship(){
for (int i=0; i < 1; i++){
board();
}
}
private void placeShipIntoShipsArray2(Ships ship) {
int row = ship.getBowRow();
int column = ship.getBowColumn();
//player1.add.ships;
player1.removeAll(player1);
player2.removeAll(player2);
//ship.clear();
if (ship.isHorizontal()) {
for (int i=0; i < ship.getLength(); i++) {
this.ships2[row][(column+i)] = ship;
}
}
else {
for (int i=0; i < ship.getLength(); i++) {
this.ships2[(row+i)][column] = ship;
}
}
}
public void display() {
System.out.print(" ");
for (int i=0; i < 9; i++) {
System.out.print(i + " ");
}
System.out.print("\n");
for (int row=0; row < 6; row++) {
System.out.print(" " + row + " ");
for (int col=0; col < 9; col++) {
String value = "";
if (this.locationsFiredUpon[row][col]) {
value = "-";
}
if (this.ships2[row][col] != null) {
value = this.ships2[row][col].toString() ;
}
else {
value = "-";
}
System.out.print(value + " ");
}
System.out.print("\n");
}
remap();
}
boolean pr = false;
boolean pr2 = false;
public void moveShip(){
System.out.println("So you wanna move a ship");
System.out.println(player1);
for (int i=0; i > 1; i++) {
print();
System.out.println("map 1");
pr = true;
}
if (pr = true){
display();
}
//ArrayList<Ships> shipsToMove = new ArrayList<>();
ArrayList<Ships> shipsToMove = new ArrayList<>();
ArrayList<Ships> shipsToMove1 = player1;
boolean notMoved = false;
int rowM = 0;
int columnM = 0;
String Tp = "1";
boolean horizontal = false;
if(notMoved = false){
System.out.println("Occupardo, you no go here");
}
System.out.println("gets here 1");
for (Ships shipM : shipsToMove1) {
System.out.println("gets here 2");
while (!notMoved) {
Scanner scanner1 = new Scanner( System.in );
System.out.println("Enter a area to move to (e.g., 2,3)");
System.out.println("please enter a movement for the: " + shipM.getShipType() + shipM.getBowRow());
String[] coordinates = scanner1.nextLine().split(",");
if (coordinates.length != 2) {
System.out.println("Please enter coordinates in the correct format.");
continue;
}
rowM = Integer.parseInt(coordinates[0].trim());
columnM = Integer.parseInt(coordinates[1].trim());
// row = random.nextInt(6);
// column = random.nextInt(9);
horizontal = true;
notMoved = shipM.okToPlaceShipAt(rowM, columnM, horizontal, this);
}
if( notMoved = true){
this.bombOp(rowM, columnM);
}
shipM.setBowColumn(columnM);
shipM.setBowRow(rowM);
shipM.setHorizontal(horizontal);
this.placeShipIntoShipsArray2(shipM);
notMoved = false;
System.out.println("");
display();
}
}
public void moveShip2(ArrayList<Ships> player2){
System.out.println("So you wanna move a ship");
for (int i=0; i > 1; i++) {
display();
pr2 = true;
}
if (pr2 = true){
display();
}
ArrayList<Ships> shipsToMove = new ArrayList<>();
player2 = this.player2;
boolean notMoved = false;
int rowM = 0;
int columnM = 0;
String Tp = "1";
boolean horizontal = false;
if(notMoved = false){
System.out.println("Occupardo, you no go here");
}
System.out.println("gets here 1");
for (Ships ship : player2) {
System.out.println("gets here 2");
while (!notMoved) {
Scanner scanner1 = new Scanner( System.in );
System.out.println("Enter a area to move to (e.g., 2,3)");
System.out.println("please enter a movement for the: " + ship.getShipType());
String[] coordinates = scanner1.nextLine().split(",");
if (coordinates.length != 2) {
System.out.println("Please enter coordinates in the correct format.");
continue;
}
rowM = Integer.parseInt(coordinates[0].trim());
columnM = Integer.parseInt(coordinates[1].trim());
// row = random.nextInt(6);
// column = random.nextInt(9);
horizontal = true;
notMoved = ship.okToPlaceShipAt(rowM, columnM, horizontal, this);
}
if( notMoved = true){
this.bombOp(rowM, columnM);
}
ship.setBowColumn(columnM);
ship.setBowRow(rowM);
ship.setHorizontal(horizontal);
this.placeShipIntoShipsArray2(ship);
notMoved = false;
System.out.println("");
display();
display();
}
}
/**
* Print the current state of the game.
*/
public void print() {
System.out.print(" ");
for (int i=0; i < 9; i++) {
System.out.print(i + " ");
}
System.out.print("\n");
for (int row=0; row < 6; row++) {
System.out.print(" " + row + " ");
for (int col=0; col < 9; col++) {
String value = "";
if (this.locationsFiredUpon[row][col]) {
value = "-";
}
**if (this.ships[row][col] != null) {
value = this.ships[row][col].toString() ;**
}
if (this.locationsFiredUpon[row][col]) {
value = this.ships2[row][col].toString();
}
if (this.ships2[row][col] != null) {
value = this.ships2[row][col].toString() ;
}
else {
value = "-";
}
System.out.print(value + " ");
}
System.out.print("\n");
}
}
public void print2() {
System.out.print(" ");
for (int i=0; i < 9; i++) {
System.out.print(i + " ");
}
System.out.print("\n");
for (int row=0; row < 6; row++) {
System.out.print(" " + row + " ");
for (int col=0; col < 9; col++) {
String value = "";
if (this.locationsFiredUpon[row][col]) {
value = "-";
}
if (this.shipsM[row][col] != null) {
value = this.shipsM[row][col].toString() ;
}
if (this.locationsFiredUpon[row][col]) {
value = this.ships2[row][col].toString();
}
if (this.ships2[row][col] != null) {
value = this.ships2[row][col].toString() ;
}
else {
value = "-";
}
System.out.print(value + " ");
}
System.out.print("\n");
}
board();
}
/**
* Handle a shot fired at the specified position.
* #param row
* #param column
* #return true if a ship was hit; else false
*/
public boolean bombOp(int row, int column) {
this.shotsFired++;
this.locationsFiredUpon[row][column] = true;
Ships shipAtLocation = this.ships[row][column];
if (shipAtLocation.isSunk()) {
return false;
}
boolean shipWasHit = shipAtLocation.bombOp(row, column);
if (shipWasHit) {
this.hitCount++;
}
if (shipAtLocation instanceof Conflict) {
return shipWasHit;
}
if (shipAtLocation.isSunk()) {
shipsSunk++;
}
return shipWasHit;
}
The best way to debug NullPointerException is to look at the first line of the stack trace, which is:
NavalBattle.Board.print(Board.java:570)
What this means is that the error occurred on line number 570 in the Board.java file. You should go to this line in the file and look at which variables could be null on that line.
Line 570 is value = this.ships2[row][col].toString();. On this line, only 3 things can possibly be null:
this.ships2
`this.ships2[row]
`this.ships2[row][col]
If you cannot immediately see which of these is null, use your IDE to set a breakpoint there and start your program in debug mode. When the IDE stops at that line, create a "watch expression" for each of the above 3 expressions, or use the "evaluate expression" feature. One of them should be null.
Without debugging, I can only guess, but I think I can make a good guess. this.ship2 is unlikely to be null because I can see that you have initialised it in your code. I also don't think that this.ships2[row] is null - You have initialised the 2D array in the constructor correctly I think. Therefore, I think it is this.ships2[row][col] that is null, and calling toString() on null is throwing the NPE. To confirm my theory you could replace the line with:
value = String.valueOf(this.ships2[row][col]);

How to implement a Multi Class Application

This is the zoo manager coding:
public class ZooManager {
public void feedAnimals(Animals a, Food[] arrayFood) {
Food temp = null;
for (int i = 0; i < arrayFood.length; i++) {
if (arrayFood[i].getFoodName().equals(a.getTypeOfFood())) {
arrayFood[i].setAmount(arrayFood[i].getAmount() - 1);
System.out.print("Animal is fed.");
}
}
System.out.print(temp);
}
public void isFoodEmpty(Food[] arrayFood) {
for (int i = 0; i < arrayFood.length; i++) {
if (arrayFood[i] == null) {
System.out.print("True");
} else {
System.out.print("False");
}
}
}
}
This is the code for the main application:
import java.util.Scanner;
public class ZooApp {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Animals[] a = new Animals[4];
for (int i = 0; i < 4; i++) {
System.out.print("Enter the animal name: ");
String an = in.nextLine();
System.out.print("What type of food do they eat: ");
String tof = in.nextLine();
a[i] = new Animals(an, tof);
}
Food[] b = new Food[3];
for (int i = 0; i < 3; i++) {
System.out.print("Enter the type of food: ");
String f = in.nextLine();
System.out.print("Enter the amount: ");
int am = in.nextInt();in.nextInt();
b[i] = new Food(f, am);
}
ZooManager z= new ZooManager();
System.out.print(z.feedAnimals(a[i], b));
System.out.print(z.isFoodEmpty(b[i]));
}
}
I have an error at the two final out prints on the main application. The first one is that "the void type is not allowed there." and "variable i can not be found." The second out put says that "isFoodEmpty cannot be given to the type: Food, required: Food[]." Thank you for any advice or help.
Your isFoodEmpty function is a void, so the first error is telling you that you can't print it because it doesn't return anything. Second, you are passing an individual instance of Food into a function that is looking for an array. That's the second error. Also note that variable i is only defined within the scope of the for loop, so you can't go using it outside of the loop.
Edit:
Currently your isFoodEmpty is a void. you have one of two options:
public void isFoodEmpty(Food[] arrayFood) {
for (int i = 0; i < arrayFood.length; i++) {
if (arrayFood[i] == null) {
System.out.print("True");
} else {
System.out.print("False");
}
}
}
}
[...]
isFoodEmpty(b); // it already prints within the function
or
public boolean isFoodEmpty(Food[] arrayFood) {
for (int i = 0; i < arrayFood.length; i++) {
if (arrayFood[i] == null) {
return true;
} else {
return false;
}
}
}
}
[...]
System.out.println(isFoodEmpty(b)); // print the boolean that it returns
Either way, you might want to check the logic on that function, since it will return empty if even one of the elements in the array is null. (You could have 20 food items, then one null value, and it would return true).

Categories

Resources