How to pass values using setter and getter among three classes - java

I've been practicing a project which is the classical Nim game. What I've achieved now is:
Add, remove, edit, display, players. (Nimsys and NimPlayer)
Selecting two players to play a game. (NimGame class)
Every time when the game ends, I need to return these two things from NimGame to NimPlayer. Then I can use getter in Nimsys:
If the player wins, his/her score +1.
Every time after a game, the number of game +1 for the player who played.
What I've already tried was to pass the "score" and "gamePlayed" from NimPlayer to NimGame, putting the getter, which is 0 at first, in the setter to set the number +1.
scores = NimPlayer.setScore(NimPlayer.getScore() + 1);
However, I don't know how to pass the "scores" here back to NimPlayer to be used. I am hoping to pass the scores back to NimPlayer. Then, I can call it from Nimsys. Here is my code.
import java.util.Scanner;
public class Nimsys {
public static String[] splitName(String inName) {
String[] splittedLine = inName.split(",");
String[] name = null;
if (splittedLine.length==3) {
String userName = splittedLine[0].trim();
String familyName = splittedLine[1].trim();
String givenName = splittedLine[2].trim();
name = new String[3];
name[0] = userName;
name[1] = familyName;
name[2] = givenName;
}
return name;
}
public static String [] splitData(String dataIn) {
String[] splittedLine = dataIn.split(",");
String[] data = null;
if (splittedLine.length==4) {
String initialStone = splittedLine[0];
String stoneRemoval = splittedLine[1];
String player1 = splittedLine[2].trim();
String player2 = splittedLine[3].trim();
data = new String[4];
data[0] = initialStone;
data[1] = stoneRemoval;
data[2] = player1;
data[3] = player2;
}
return data;
}
public static String playerChecker(String name) {
String player = null;
for (int i = 0; i < NimPlayer.getId(); i++) {
player = NimPlayer.getPlayer()[i].getUserName();
if (player.equals(name)) {
break;
}
}
return player;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (true) {
System.out.print('$');
String commandin = in.next();
if (commandin.equals("addplayer")) {
String inName = in.nextLine();
String[] name = splitName(inName);
//Make sure the vadality of in name
//Can use playerCheck to simplify the code
if (name!=null && name.length==3) {
for (int i = 0; i < NimPlayer.getId(); i ++) {
String userCheck = NimPlayer.getPlayer()[i].getUserName();
if (userCheck.contains(name[0])) {
System.out.println("The player already exist");//Test if player has been created
}
}
NimPlayer.createPlayer(name[0], name[1], name[2], 0, 0);
System.out.println("The player has been created.");
} else {
System.out.println("Not Valid! Please enter again!");
}
}
if (commandin.equals("removeplayer")) {
//cannot loop through the entire null array, would be NullPointerException
String removeUserName = in.nextLine().trim();
/*System.out.println("Are you sure you want to remove all players? (y/n) \n");
//System.out.print('$');
commandin = in.next();
if (commandin.equals("y")) {
for (int i = 0; i < NimPlayer.getId(); i++) {
NimPlayer.getPlayer()[i] = null;
System.out.println("Remove all the players");
}
} else {
System.out.print('$');
}*/
//commandin = in.next();
for (int i = 0; i < NimPlayer.getId(); i++) {
String userName = NimPlayer.getPlayer()[i].getUserName().trim();
if (removeUserName != null && userName.equals(removeUserName)) {
NimPlayer.getPlayer()[i] = null;
System.out.println("Remove successfully!");// A test to see if the code runs
} else {
System.out.println("The player does not exist");
}
}
}
if (commandin.equals("editplayer")) {
String inName = in.nextLine();
String[] splittedLine = inName.split(",");
if (splittedLine!=null && splittedLine.length==3) {
String userName = splittedLine[0].trim();
String familyName = splittedLine[1].trim();
String givenName = splittedLine[2].trim();
//System.out.println(userName+","+familyName+","+givenName);//Test if in name in the if loop
for (int i = 0; i < NimPlayer.getId(); i++) {
String userCheck = NimPlayer.getPlayer()[i].getUserName().trim();
if (userName != null && userCheck.equals(userName)) {
NimPlayer.getPlayer()[i].setFamilyName(familyName);
NimPlayer.getPlayer()[i].setGivenName(givenName);
System.out.println("Edit successfully");
} else {
System.out.println("The player does not exist.");
}
}
} else {
System.out.println("Invalid in! Please enter again.");
}
}
if (commandin.equals("displayplayer")) {
String user = in.nextLine().trim();
for (int i = 0; i < NimPlayer.getId(); i++) {
String userCheck = NimPlayer.getPlayer()[i].getUserName().trim();
String userName = NimPlayer.getPlayer()[i].getUserName();
String familyName = NimPlayer.getPlayer()[i].getfamilyName();
String givenName = NimPlayer.getPlayer()[i].getGivenName();
int score = NimPlayer.setScore(NimPlayer.getScore());
int gamePlayed = NimPlayer.setGamePlayed(NimPlayer.getGamePlayed());
if (user != null && userCheck.equals(user)) {
System.out.println(userName+","+familyName+","+givenName+","+gamePlayed+" games,"+score +" wins");
}
}
}
if (commandin.equals("startgame")) {
String dataIn = null, player1 = null, player2 = null;
do {
dataIn = in.nextLine();
String [] data = splitData(dataIn);
if (data != null && data.length==4) {
player1 = playerChecker(data[2]);
player2 = playerChecker(data[3]);
NimGame game = new NimGame(data[0].trim(), data[1], player1, player2);
game.playGame(data[0].trim(), data[1], player1, player2);
}
} while(player1 == null || player2 == null);
}
}
}
}
The above is my main method Nimsys. I have a problem calling these values using the displayplayer command. It should be like this:
userName,familyName,givenName,gamePlayed "games",score "wins"
Below is my NimPlayer class:
//username, given name, family name, number of game played, number of games won
public class NimPlayer {
private String userName;
private String familyName;
private String givenName;
private static int score;
private static int gamePlayed;
static int id;
static NimPlayer[] playerList = new NimPlayer[10]; // set an array here
//define NimPlayer data type
public NimPlayer(String userName, String surName, String givenName, int gamePlayed, int score) {
this.userName = userName;
this.familyName = surName;
this.givenName = givenName;
NimPlayer.score = score;
NimPlayer.gamePlayed = gamePlayed;
}
// create new data using NimPlayer data type
public static void createPlayer(String userName, String familyName, String givenName, int gamePlayed, int score) {
if (id<10) {
playerList[id++] = new NimPlayer(userName, familyName, givenName, gamePlayed, score);
} else {
System.out.println("Cannot add more players.");
}
}
public static int getId() {
return id;
}
public static NimPlayer [] getPlayer() {
return playerList;
}
public void setUserName(String userName) {
this.userName = userName;
}
public void setFamilyName(String familyName) {
this.familyName = familyName;
}
public void setGivenName(String givenName) {
this.givenName = givenName;
}
public String getUserName() {
return userName;
}
public String getfamilyName() {
return familyName;
}
public String getGivenName() {
return givenName;
}
public static int setScore(int score) {
return score;
}
public static int getScore() {
return score;
}
public static int setGamePlayed (int gamePlayed) {
return gamePlayed;
}
public static int getGamePlayed() {
return gamePlayed;
}
}
And finally the NimGame part:
import java.util.Scanner;
//playing process
//current stone count
//upper bound on stone removal
//two players
public class NimGame {
private static int gamePlayed;
private static int scores;
String player1;
String player2;
String playOrNot;
String initialStoneInput;
String dataRemoval;
int stars;
int stoneBalance;
int initialStone;
int upperBound;
public int initializeStone(int startStones) {
stoneBalance = startStones;
return stoneBalance;
}
public void removeStones(int stonesTaken) {
int updatedBalance = stoneBalance - stonesTaken;
stoneBalance = updatedBalance;
}
public void printStar(int star) {
stars = star;
stars = stoneBalance;
for (int stars = 1; stars <= star; stars++) {
System.out.print(" *");
}
System.out.println();
}
public static int earnPoint(String player) {
for (int i = 0; i < NimPlayer.getId(); i++) {
String playerCheck = NimPlayer.getPlayer()[i].getUserName();
if (playerCheck.equals(player)) {
scores = NimPlayer.setScore(NimPlayer.getScore() + 1);
}
}
return scores;
}
public static int gamePlayed(String player) {
for (int i = 0; i < NimPlayer.getId(); i++) {
String playerCheck = NimPlayer.getPlayer()[i].getUserName();
if (playerCheck.equals(player)) {
gamePlayed = NimPlayer.setGamePlayed(NimPlayer.getGamePlayed() + 1);
}
}
return gamePlayed + 1;
}
public int getGameScore() {
return scores;
}
public int getNumberGamePlayed() {
return gamePlayed;
}
public NimGame (String initialStone ,String dataRemoval,String player1, String player2) {
this.initialStoneInput = initialStone;
this.dataRemoval = dataRemoval;
this.player1 = player1;
this.player2 = player2;
}
Scanner in = new Scanner(System.in);
public void playGame (String initialStone ,String dataRemoval,String player1, String player2) {
//Convert user input string into integer
int initialStoneInt = Integer.parseInt(initialStoneInput);
initializeStone(initialStoneInt);
int upperBound = Integer.parseInt(dataRemoval);
System.out.println("Initial stone count: "+initialStoneInt);
System.out.println("Maximum stone removal: "+dataRemoval);
System.out.println("Player 1: "+player1);
System.out.println("Player 2: "+player2);
do {
// while stoneBalance > 0, two players keep playing the game
while (stoneBalance > 0) {
// player1's turn and remove the stones; decision of winning
System.out.println(player1 + "'s turn - remove how many?\n");
int takeStone = in.nextInt();
while (takeStone > upperBound || takeStone <= 0) {
System.out.println(
"Invalid, you need to remove stones under upper "+
"bound limit or above 0. \n Please enter again.");
takeStone = in.nextInt();
}
removeStones(takeStone); //remove the stone
if (stoneBalance > 0) {
//show the remaining stones
System.out.print(stoneBalance + " stones left:");
printStar(stoneBalance);
} else if (stoneBalance <= 0) {
System.out.println("Game Over\n" + player2 + " wins!\n");
earnPoint(player2);
break;
}
// player2's turn and remove the stones; decision of winning
System.out.println(player2 + "'s turn - remove how many?\n");
takeStone = in.nextInt();
while (takeStone > upperBound || takeStone <= 0) {
System.out.println(
"Invalid, you need to remove stones under upper " +
"bound limit or above 0. \n Please enter again.");
takeStone = in.nextInt();
}
removeStones(takeStone);
if (stoneBalance > 0) {
System.out.print(stoneBalance + " stones left:");
printStar(stoneBalance);
} else if (stoneBalance <= 0) {
System.out.println("Game Over\n" + player1 + " wins!\n");
earnPoint(player1);
break;
}
}
// ask players to play again
//in.nextLine();
System.out.println("Do you want to play again (Y/N):");
playOrNot = in.nextLine();
gamePlayed(player1);
gamePlayed(player2);
} while (playOrNot.equals("Y"));
}
}

I completely reworked your model code, which made the rest of the code simpler. Creating a good application model makes creating the rest of the application much easier.
Here's your reworked NimPlayer class. The fields that make up this class all have to do with a game player.
The class consists solely of getters and setters. Two of the setters add instead of replace. There are no static fields in this class.
public class NimPlayer {
private final int id;
private final String userName;
private String familyName;
private String givenName;
private int gamesPlayed;
private int gamesWon;
public NimPlayer(int id, String userName, String familyName,
String givenName) {
this.id = id;
this.userName = userName;
this.familyName = familyName;
this.givenName = givenName;
this.gamesPlayed = 0;
this.gamesWon = 0;
}
public int getId() {
return id;
}
public String getUserName() {
return userName;
}
public String getFamilyName() {
return familyName;
}
public void setFamilyName(String familyName) {
this.familyName = familyName;
}
public String getGivenName() {
return givenName;
}
public void setGivenName(String givenName) {
this.givenName = givenName;
}
public int getGamesPlayed() {
return gamesPlayed;
}
public void addGamePlayed() {
this.gamesPlayed++;
}
public int getGamesWon() {
return gamesWon;
}
public void addGamesWon() {
this.gamesWon++;
}
}
I created a new class, NimModel to hold the state of the game. This class is where the playerList, and all the code associated with the playerList, resides.
Making playerList a List would have simplified the code, but I left playerList as an array to show you the code involved in adding and removing players from an array.
public class NimModel {
private int numberOfPlayers;
private int limit;
private NimPlayer[] playerList;
public NimModel() {
this.numberOfPlayers = 0;
this.limit = 10;
this.playerList = new NimPlayer[limit];
}
public boolean createPlayer(String userName, String familyName,
String givenName) {
if (numberOfPlayers < limit) {
int id = getFirstPlayerSlot();
if (id >= 0) {
playerList[id] = new NimPlayer(id,
userName, familyName, givenName);
numberOfPlayers++;
}
return true;
} else {
return false;
}
}
private int getFirstPlayerSlot() {
for (int i = 0; i < limit; i++) {
if (playerList == null) {
return i;
}
}
return -1;
}
public NimPlayer getPlayer(int id) {
return playerList[id];
}
public NimPlayer getPlayer(String userName) {
for (int i = 0; i < limit; i++) {
if (playerList[i] != null) {
if (userName.equals(playerList[i].getUserName())) {
return playerList[i];
}
}
}
return null;
}
public NimPlayer removePlayer(String userName) {
for (int i = 0; i < limit; i++) {
NimPlayer player = playerList[i];
if (player != null) {
if (userName.equals(player.getUserName())) {
this.playerList[i] = null;
numberOfPlayers--;
return player;
}
}
}
return null;
}
public int getNumberOfPlayers() {
return numberOfPlayers;
}
}
Finally, here are your reworked Nimsys and NimGame classes. Again, we've removed all of the static references.
It makes code a lost easier to read and understand if you code methods in the order that they're called. In other words, present the main points first, then the details.
import java.util.Scanner;
public class Nimsys {
private NimModel nimModel;
public static void main(String[] args) {
Nimsys nimsys = new Nimsys();
nimsys.processCommands();
}
private void processCommands() {
this.nimModel = new NimModel();
Scanner in = new Scanner(System.in);
while (true) {
System.out.print('$');
String commandin = in.nextLine().trim();
if (commandin.equalsIgnoreCase("addplayer")) {
addPlayer(in);
}
if (commandin.equalsIgnoreCase("removeplayer")) {
removePlayer(in);
}
if (commandin.equalsIgnoreCase("editplayer")) {
editPlayer(in);
}
if (commandin.equalsIgnoreCase("displayplayer")) {
displayPlayer(in);
}
if (commandin.equalsIgnoreCase("startgame")) {
startGame(in);
}
}
}
private void addPlayer(Scanner in) {
String inName = in.nextLine().trim();
String[] name = splitName(inName);
if (name != null && name.length == 3) {
NimPlayer player = nimModel.getPlayer(name[0]);
if (player == null) {
nimModel.createPlayer(name[0], name[1], name[2]);
System.out.println("The player has been created.");
} else {
System.out.println("The player is already in "
+ "the list.");
}
} else {
System.out.println("Not Valid! Please enter again!");
}
}
private String[] splitName(String inName) {
String[] splittedLine = inName.split(",");
String[] name = null;
if (splittedLine.length == 3) {
String userName = splittedLine[0].trim();
String familyName = splittedLine[1].trim();
String givenName = splittedLine[2].trim();
name = new String[3];
name[0] = userName;
name[1] = familyName;
name[2] = givenName;
}
return name;
}
private void removePlayer(Scanner in) {
String removeUserName = in.nextLine().trim();
NimPlayer player = nimModel.removePlayer(removeUserName);
if (player == null) {
System.out.println("The player does not exist");
} else {
System.out.println("Player " + player.getUserName() +
" removed successfully!");
}
}
private void editPlayer(Scanner in) {
String inName = in.nextLine().trim();
String[] splittedLine = inName.split(",");
if (splittedLine != null && splittedLine.length == 3) {
String userName = splittedLine[0].trim();
String familyName = splittedLine[1].trim();
String givenName = splittedLine[2].trim();
NimPlayer player = nimModel.getPlayer(userName);
if (player == null) {
System.out.println("The player does "
+ "not exist.");
} else {
player.setFamilyName(familyName);
player.setGivenName(givenName);
System.out.println("Edited successfully");
}
} else {
System.out.println("Invalid user name! Please "
+ "enter again.");
}
}
private void displayPlayer(Scanner in) {
String userName = in.nextLine().trim();
NimPlayer player = nimModel.getPlayer(userName);
String familyName = player.getFamilyName();
String givenName = player.getGivenName();
int gamesWon = player.getGamesWon();
int gamesPlayed = player.getGamesPlayed();
System.out.println(userName + "," + familyName +
"," + givenName + "," + gamesPlayed +
" games," + gamesWon + " wins");
}
private void startGame(Scanner in) {
NimPlayer player1 = null, player2 = null;
do {
String dataIn = in.nextLine().trim();
String[] data = splitData(dataIn);
if (data != null && data.length == 4) {
player1 = nimModel.getPlayer(data[2]);
player2 = nimModel.getPlayer(data[3]);
NimGame game = new NimGame(nimModel, data[0],
data[1], player1, player2);
game.playGame();
}
} while (player1 == null || player2 == null);
}
private String[] splitData(String dataIn) {
String[] splittedLine = dataIn.split(",");
String[] data = null;
if (splittedLine.length == 4) {
String initialStone = splittedLine[0];
String stoneRemoval = splittedLine[1];
String player1 = splittedLine[2].trim();
String player2 = splittedLine[3].trim();
data = new String[4];
data[0] = initialStone;
data[1] = stoneRemoval;
data[2] = player1;
data[3] = player2;
}
return data;
}
}
NimGame class
import java.util.Scanner;
public class NimGame {
NimPlayer player1;
NimPlayer player2;
String playOrNot;
String initialStoneInput;
String dataRemoval;
int stars;
int stoneBalance;
int initialStone;
int upperBound;
public NimGame(NimModel nimModel, String initialStoneInput,
String dataRemoval,
NimPlayer player1, NimPlayer player2) {
this.initialStoneInput = initialStoneInput;
this.dataRemoval = dataRemoval;
this.player1 = player1;
this.player2 = player2;
}
Scanner in = new Scanner(System.in);
public void playGame() {
// Convert user input string into integer
int initialStoneInt = Integer.parseInt(initialStoneInput);
initializeStone(initialStoneInt);
int upperBound = Integer.parseInt(dataRemoval);
System.out.println("Initial stone count: " +
initialStoneInt);
System.out.println("Maximum stone removal: " +
dataRemoval);
System.out.println("Player 1: " + player1.getUserName());
System.out.println("Player 2: " + player2.getUserName());
do {
// while stoneBalance > 0, two players
// keep playing the game
while (stoneBalance > 0) {
// player1's turn and remove the stones;
// decision of winning
System.out.println(player1.getUserName() + "'s "
+ "turn - remove how many?\n");
int takeStone = in.nextInt();
while (takeStone > upperBound ||
takeStone <= 0) {
System.out.println("Invalid, you need "
+ "to remove stones under upper "
+ "bound limit or above 0. \n"
+ "Please enter again.");
takeStone = in.nextInt();
}
removeStones(takeStone); // remove the stone
if (stoneBalance > 0) {
// show the remaining stones
System.out.print(stoneBalance +
" stones left:");
printStar(stoneBalance);
} else if (stoneBalance <= 0) {
System.out.println("Game Over\n" +
player2.getUserName() + " wins!\n");
earnPoint(player2);
break;
}
// player2's turn and remove the stones;
// decision of winning
System.out.println(player2.getUserName() + "'s "
+ "turn - remove how many?\n");
takeStone = in.nextInt();
while (takeStone > upperBound ||
takeStone <= 0) {
System.out.println("Invalid, you need "
+ "to remove stones under upper "
+ "bound limit or above 0. \n"
+ "Please enter again.");
takeStone = in.nextInt();
}
removeStones(takeStone);
if (stoneBalance > 0) {
System.out.print(stoneBalance + " "
+ "stones left:");
printStar(stoneBalance);
} else if (stoneBalance <= 0) {
System.out.println("Game Over\n" +
player1.getUserName() + " wins!\n");
earnPoint(player1);
break;
}
}
player1.addGamePlayed();
player2.addGamePlayed();;
// ask players to play again
// in.nextLine();
System.out.println("Do you want to play "
+ "again (Y/N):");
playOrNot = in.nextLine().trim();
} while (playOrNot.equalsIgnoreCase("Y"));
}
public int initializeStone(int startStones) {
stoneBalance = startStones;
return stoneBalance;
}
public void removeStones(int stonesTaken) {
int updatedBalance = stoneBalance - stonesTaken;
stoneBalance = updatedBalance;
}
private void printStar(int star) {
stars = star;
stars = stoneBalance;
for (int stars = 1; stars <= star; stars++) {
System.out.print(" *");
}
System.out.println();
}
private int earnPoint(NimPlayer player) {
player.addGamesWon();
return player.getGamesWon();
}
}

The following things need to be addressed in your code:
Since you are creating a NimPlayer using createPlayer, make the following constructor private and also create a private no-arg constructor so that there is no other way than using createPlayer to create a NimPlayer.
Change it to:
private NimPlayer(String userName, String surName, String givenName) {
this.userName = userName;
this.familyName = surName;
this.givenName = givenName;
}
Remove the parameters, int gamePlayed and int score from createPlayer because when you create a NimPlayer, the player does not have any data for gamePlayed and score. These things will be set during the course of game.
Change it to:
public static void createPlayer(String userName, String familyName, String givenName) {
if (id<10) {
playerList[id++] = new NimPlayer(userName, familyName, givenName);
} else {
System.out.println("Cannot add more players.");
}
}
Since score and gamePlayed belong to individual players i.e. each individual player will have his/her score and gamePlayed independent from those of other players, these attributes need to be non-static. You should create a static variable only when the value of the variable is supposed to be same for all instances e.g. NimPlayer[] playerList or id. Note that I had asked you earlier to use the name, counter instead of id because it is supposed to be a counter for the no. of players and therefore the name, id is confusing. If you want to create an id field for individual players, use the Replace All feature of your IDE to replace all occurances of id with counter, all occurances of Id with Counter (for replacing getters and setters) and then create a non-static private int id; like firstName, familyName etc. inside NimPlayer.
Declare score and gamePlayed as follows:
private int score;
private int gamePlayed;
//public getters and setters of score and gamePlayed
score and gamePlayed should be accessed the way you are accessing names
if (commandin.equals("displayplayer")) {
String user = in.nextLine().trim();
NimPlayer [] players = NimPlayer.getPlayer();
for (int i = 0; i < NimPlayer.getId(); i++) {
String userCheck = players[i].getUserName().trim();
String userName = players[i].getUserName();
String familyName = players[i].getFamilyName();
String givenName = players[i].getGivenName();
int score = players[i].getScore();
int gamePlayed = players[i].getGamePlayed();
if (user != null && userCheck.equals(user)) {
System.out.println(userName + "," + familyName + "," + givenName + "," + gamePlayed + " games,"
+ score + " wins");
}
}
}
The value of score should be set as
public static int earnPoint(String player) {
int i = 0;
for (i = 0; i < NimPlayer.getCounter(); i++) {
String playerCheck = NimPlayer.getPlayer()[i].getUserName();
if (playerCheck.equals(player)) {
NimPlayer.getPlayer()[i].setScore(NimPlayer.getPlayer()[i].getScore() + 1);
break;
}
}
return NimPlayer.getPlayer()[i].getScore();
}

Related

How to resolve null pointer exception in code? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 12 months ago.
I'm working on a project that involves three code files: a class for passengers - Passenger.java, a class for the airplane itself - Airplane.java, and a driver class - RunAirplane.java. 5 passengers have been added using the Passenger instantiation in main along with a count of the passengers that I plan on updating later so it is not limited to 5. The issue is that I keep getting a NullPointerException error whenever I run the main file in IntelliJ and cant find out why. The error code says it's happening on line 58 of the Airplane.java file which leads me to assume that it's because of the addPassenger method.
Passenger Class (if needed)
public class Passenger {
private String name;
private int birthYear;
private double weight;
private char gender;
private int numCarryOn;
//Default constructor
public Passenger(){
name = "";
birthYear = 1900;
weight = 0.0;
gender = 'u';
numCarryOn = 0;
}
//Alt default constructor
public Passenger(String newName, int newBirthYear, double newWeight, char newGend, int newNumCarryOn){
this.setName(newName);
this.setBirthYear(newBirthYear);
this.setWeight(newWeight);
this.setGender(newGend);
this.setNumCarryOn(newNumCarryOn);
}
//Calculate age
public int calculateAge(int currentYear){
int age = 0;
if (currentYear < birthYear){
return -1;
}
else {
age = currentYear - birthYear;
}
return age;
}
//Gain weight
public void gainWeight(){
weight += 1;
}
//Gain weight based on input
public void gainWeight(double pounds){
if (weight > 0){
weight = weight + pounds;
}
}
//Get birthYear
public int getBirthYear(){
return birthYear;
}
//Get gender
public char getGender(){
return gender;
}
//Get name
public String getName(){
return name;
}
//Get weight
public double getWeight(){
return weight;
}
//Get numCarryOn
public int getNumCarryOn(){
return numCarryOn;
}
//isFemale
public boolean isFemale(){
if (gender == 'f'){
return true;
}
else {
return false;
}
}
//isMale
public boolean isMale(){
if (gender == 'm'){
return true;
}
else {
return false;
}
}
//loseWeight
public void loseWeight(){
if (weight > 0){
weight -= 1;
}
}
//lose weight by value
public void loseWeight(double weight2lose){
if (weight - weight2lose >= 0){
weight -= weight2lose;
}
}
//print
public void printDetails(){
System.out.printf("Name: %20s | Year of Birth: %4d | Weight: %10.2f | Gender: %c | NumCarryOn: %2d\n", name, birthYear, weight, gender, numCarryOn);
}
//setGender
public void setGender(char newGender){
if (newGender == 'f' || newGender == 'm') {
this.gender = newGender;
} else {
this.gender = 'u';
}
}
//setName
public void setName(String newName){
name = newName;
}
//setBirthYear
public void setBirthYear(int newBY){
birthYear = newBY;
}
//setWeight
public void setWeight(double newWeight){
if (newWeight < 0){
weight = -1;
}
else {
weight = newWeight;
}
}
//setNumCarryOn
public void setNumCarryOn(int newNumCarryOn){
if (newNumCarryOn < 0){
numCarryOn = 0;
}
else if (newNumCarryOn > 2){
numCarryOn = 2;
}
else {
numCarryOn = newNumCarryOn;
}
}
}
Airplane Class
import java.util.Arrays;
public class Airplane {
private Passenger[] passengers;
private String airplaneName;
private int numPassengers;
public int count = 0;
//default constructor
public Airplane(){
airplaneName = "";
passengers = new Passenger[100];
numPassengers = 0;
}
//default constructor with String input
public Airplane(String otherairplaneName){
airplaneName = otherairplaneName;
passengers = new Passenger[100];
numPassengers = 0;
}
//default constructor with int input
public Airplane(int otherArraySize){
airplaneName = "";
if (otherArraySize < 0){
otherArraySize = 0;
passengers = new Passenger[otherArraySize];
}
numPassengers = 0;
}
//default constructor with String and int input
public Airplane(String otherAirplaneName, int otherArraySize){
airplaneName = otherAirplaneName;
if (otherArraySize < 0){
otherArraySize = 0;
passengers = new Passenger[otherArraySize];
}
numPassengers = 0;
}
//add a passenger
public void addPassenger(Passenger a){
for (int i = 0; i < passengers.length; i++){
if (passengers.length - count >= 0){
passengers[i] = a;
break;
}
}
}
}
Driver
public class RunAirplane {
public static void main(String[] args) {
Airplane a1 = new Airplane("Flight 1", 100);
Passenger p1 = new Passenger("Albert", 1879, 198.5, 'm', 2);
Passenger p2 = new Passenger("Grace", 1906, 105, 'f', 1);
Passenger p3 = new Passenger("Tim", 1955, 216.3, 'm', 2);
Passenger p4 = new Passenger("Steve", 1955, 160, 'm', 2);
Passenger p5 = new Passenger("Sergey", 1973, 165.35, 'm', 1);
a1.addPassenger(p1);
a1.count += 1;
a1.addPassenger(p2);
a1.count += 1;
a1.addPassenger(p3);
a1.count += 1;
a1.addPassenger(p4);
a1.count += 1;
a1.addPassenger(p5);
a1.count += 1;
a1.printAllDetails();
}
}
You are trying to access the global variable passengers which is getting initialized only when the parameter otherArraySize is smaller than 0 as specified in the constructor that you are using. Try reversing the condition for that parameter. This way your array would initialize.
public Airplane(String otherAirplaneName, int otherArraySize){
airplaneName = otherAirplaneName;
if (otherArraySize > 0){
otherArraySize = 0;
passengers = new Passenger[otherArraySize];
}
numPassengers = 0;
}

Looping through ArrayList of object to find the highest value and return the details

I want to create a method which calculates and displays the highest overall crime stats. Eg to output something like:
*City with highest crime stats 204451 is New York
City : New York
State : NY
Population : 8165001
Murder : 596
Robbery : 23511
Assault : 26908
Burglary : 22137
Larceny : 115363
Car theft : 15936
Violent crime : 51015
Possession crime : 153436*
I have one class StartApp.java which the ArrayList of CityCrime type, and it reads the crime stats from a csv file:
public static ArrayList<CityCrime> crimes = new ArrayList<CityCrime>();
public static void readCrimeData() {
File file = new File("crimeUSA.csv");
FileReader fileReader;
BufferedReader bufferedReader;
String crimeInfo;
String[] stats;
try {
fileReader = new FileReader(file);
bufferedReader = new BufferedReader(fileReader);
crimeInfo = bufferedReader.readLine();
crimeInfo = bufferedReader.readLine();
do {
CityCrime crime = new CityCrime(); // Default constructor
stats = crimeInfo.split(",");
{
if(stats[0] != null) {
crime.setCity(stats[0]);
}
if(stats[1] != null) {
crime.setState(stats[1]);
}
if(stats[2] != null) {
if(Integer.parseInt(stats[2]) >=0) {
crime.setPopulation(Integer.parseInt(stats[2]));
}
}
if(stats[3] != null) {
if(Integer.parseInt(stats[3]) >=0) {
crime.setMurder(Integer.parseInt(stats[3]));
}
}
if(stats[4] != null) {
if(Integer.parseInt(stats[4]) >=0) {
crime.setRobbery(Integer.parseInt(stats[4]));
}
}
if(stats[5] != null) {
if(Integer.parseInt(stats[5]) >=0) {
crime.setAssault(Integer.parseInt(stats[5]));
}
}
if(stats[6] != null) {
if(Integer.parseInt(stats[6]) >=0) {
crime.setBurglary(Integer.parseInt(stats[6]));
}
}
if(stats[7] != null) {
if(Integer.parseInt(stats[7]) >=0) {
crime.setLarceny(Integer.parseInt(stats[7]));
}
}
if(stats[8] != null) {
if(Integer.parseInt(stats[8]) >=0) {
crime.setMotorTheft(Integer.parseInt(stats[8]));
}
}
}
crimes.add(crime);
System.out.println(crime);
crimeInfo = bufferedReader.readLine();
} while (crimeInfo != null);
fileReader.close();
bufferedReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void showMenu() {
Scanner menuSelect = new java.util.Scanner(System.in);
System.out.println("1. Display all crime stats by city");
System.out.println("2. Display all crime stats by selected city");
System.out.println("3. Display the murder stats by selected state ");
System.out.println("4. Display highest crime city - all crimes");
System.out.println("5. Display each state (in alphabetical order with the number of car thefts ");
System.out.println("6. Write / export all cities in descending order of Robbery rate ");
System.out.println("7. Quit");
System.out.println("Enter option 1-7");
//int option = menuSelect.nextInt();
Scanner scanner = new Scanner(System.in);
int option = Integer.parseInt(menuSelect.next());
switch(option) {
case 1:
displayAllCityCrimeStats();
break;
case 2:
System.out.println("Enter city");
String cityOption = menuSelect.next();
displayCityByName(cityOption);
break;
case 3:
System.out.println("Enter state");
String stateOption = menuSelect.next();
displayMurdersByState(stateOption);
break;
case 4:
//displayHighest();
displayCityHighestCrimeStats();
break;
case 5:
displayStateCarThefts();
break;
case 6:
return; // System.exit(0) or quit however you want to
default:
option = Integer.parseInt(scanner.next());
}
}
Then in CityCrime.java I have:
public class CityCrime {
//Instance variables
private String city;
private String state;
private int population;
private int murder;
private int robbery;
private int assault;
private int burglary;
private int larceny;
private int motorTheft;
public int totalCrimes;
public static void main(String[] args) {
}
public int getTotalCrimes() {
return totalCrimes;
}
public int setTotalCrimes(int murder, int robbery, int assault, int burglary, int larceny, int motorTheft) {
this.totalCrimes = murder + robbery + assault + burglary + larceny + motorTheft;
return totalCrimes;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
if(state.equalsIgnoreCase("ALABAMA")) {
this.state = "AL";
}
//etc
}
public int getPopulation() {
return population;
}
public void setPopulation(int population) {
this.population = population;
}
public int getMurder() {
return murder;
}
public void setMurder(int murder) {
this.murder = murder;
}
public int getRobbery() {
return robbery;
}
public void setRobbery(int robbery) {
this.robbery = robbery;
}
public int getAssault() {
return assault;
}
public void setAssault(int assault) {
this.assault = assault;
}
public int getBurglary() {
return burglary;
}
public void setBurglary(int burglary) {
this.burglary = burglary;
}
public int getLarceny() {
return larceny;
}
public void setLarceny(int larceny) {
this.larceny = larceny;
}
public int getMotorTheft() {
return motorTheft;
}
public void setMotorTheft(int motorTheft) {
this.motorTheft = motorTheft;
}
public static void showAllMurderDetails() {
for (CityCrime crime : StartApp.crimes) {
System.out.println("Crime: City= " + crime.getCity() + ", Murder= " + crime.getMurder());
}
System.out.println();
}
public static int showAllViolentCrimes() {
int total = 0;
for(CityCrime crime : StartApp.crimes) {
total=total+crime.getMurder();
total=total+crime.getRobbery();
total=total+crime.getAssault();
}
System.out.println("Total of violent crimes: " + total);
return total;
}
public static int getPossessionCrimes() {
int total=0;
for (CityCrime crime : StartApp.crimes) {
total = total + crime.getBurglary();
total = total + crime.getLarceny();
total = total + crime.getMotorTheft();
}
System.out.println("Total of possession crimes: " + total);
return total;
}
}
I have tried a lot of different things so far but I just can't seem to figure it out, and I've been deep into the google pages. I'd really appreciate help with this function. I do almost understand why the way I'm trying is not working, as I write it I know it isn't going to work. A couple of what I've tried is the following: (please try to ignore the mess of it-I've changed things 100 times)
public static void displayHighest() {
int crimeStatCurrent = 0;
int crimeStatPrev = 0;
int crimeStatCurrent1 = 0;
int highest = 0;
String highestCity = "";
boolean flag;
CityCrime crimeStat = null;
for(CityCrime crime : crimes) {
/*
* crimeStatCurrent = crimeStatCurrent + crime.getAssault();; crimeStatCurrent =
* crimeStatCurrent + crime.getBurglary(); crimeStatCurrent = crimeStatCurrent +
* crime.getLarceny(); crimeStatCurrent = crimeStatCurrent +
* crime.getMotorTheft(); crimeStatCurrent = crimeStatCurrent +
* crime.getMurder(); crimeStatCurrent = crimeStatCurrent + crime.getRobbery();
*/
crimeStatCurrent = crime.setTotalCrimes(crime.getMurder(), crime.getRobbery(), crime.getAssault(), crime.getBurglary(), crime.getLarceny(), crime.getMotorTheft());
if(crime.getTotalCrimes() > crimeStatPrev) {
highest = crimeStatCurrent;
highestCity = crime.getCity();
System.out.println("Highest City" + highestCity);
}
}
}
public static void displayCityHighestCrimeStats() {
int crimeStat = 0;
int prevCrimeStat = 0;
int highestCrimeStat = 0;
int CurrentCrimeStat;
String highestCity = "";
int i;
for(CityCrime crime : crimes) {
/*
* crimeStat = crimeStat + crime.getAssault();; crimeStat = crimeStat +
* crime.getBurglary(); crimeStat = crimeStat + crime.getLarceny(); crimeStat =
* crimeStat + crime.getMotorTheft(); crimeStat = crimeStat + crime.getMurder();
* crimeStat = crimeStat + crime.getRobbery();
*/
//crimeStat = crime.setTotalCrimes(crime.getMurder(), crime.getRobbery(), crime.getAssault(), crime.getBurglary(), crime.getLarceny(), crime.getMotorTheft());
for(i = 0; i < crimes.size(); i++) {
if(crime.setTotalCrimes(crime.getMurder(), crime.getRobbery(), crime.getAssault(), crime.getBurglary(), crime.getLarceny(), crime.getMotorTheft()) > prevCrimeStat) {
highestCity = crime.getCity();
highestCrimeStat = crime.getTotalCrimes();
}
else if(crime.setTotalCrimes(crime.getMurder(), crime.getRobbery(), crime.getAssault(), crime.getBurglary(), crime.getLarceny(), crime.getMotorTheft()) < prevCrimeStat) {
}
prevCrimeStat = crimeStat;
}
System.out.println("Crime Stat: " + crimeStat + "for " + crime.getCity());
}
//System.out.println("City with highest crime stats is " + highestCity + " with " + crimeStat);
}
Okay, this is the method I have now:
public CityCrime highestCrimeCity(List<CityCrime> cities) {
return cities
// Create a stream from the list of cities
.stream()
// Sort by totalCrime in reverse order
.sorted(Comparator.comparingInt(CityCrime::getTotalCrimes).reversed()
// Take the first city if it exists (you could pass an empty array)
.findFirst()
// If the city exists return it, otherwise null
.orElseNull();
}
for 'FindFirst' I am getting the error:
The method findFirst() is undefined for the type Comparator
Really appreciate all help/comments.
My tip is to maintain a clean code:
Each method of your code should solve a single task. Code will be easier to read and maintain also by people who never saw it before
Try to use logger instead of System.out methods. This give you a lot more flexibility
Use existing methods when possible instead of rewriting them. Don't reinvent the wheel
Try to use "new" (not really new, it comes in java 8) stream construct when possible. The code will be easier to read and maintain
Do not use instances variables when possible, but pass data as parameters. The code will be easier to understand and less affected by side effects
In particular you can do something like that:
// This method just calculate the City with highest crime (single task)
// It takes cities as a parameter, no other data are needed (pass parameters instead of using instance variables)
// It uses stream of java 8 (prefer using stream over loops)
// It uses sorted method (use existing methods when possible)
// It uses Optional
public CityCrime highestCrimeCity(List<CityCrime> cities) {
return cities
// Create a stream from the list of cities
.stream()
// Sort by totalCrime in reverse order
.sorted(Comparator.comparingInt(CityCrime::getTotalCrime).reversed()
// Take the first city if it exists (you could pass an empty array)
.findFirst()
// If the city exists return it, otherwise null
.orElseNull();
}
Than you can call it to print the output as follow:
CityCrime badCity = highestCityCrime(cities);
System.out.println("The baddest city is " + badCity.getCity() + " with " + badCity.getTotalCrimes() + " crimes");
When you configured a logger you can replace the System.out.println with LOGGER.info

Why won't my bubble sort sort my array of objects?

I've created a program with an object called CarlysCatering. I'm trying to sort the CarlysCatering objects by number of guests.
I've tried using a bubble sort but I get an error message.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
CarlysCatering[] event = new CarlysCatering[100];
event[0] = new CarlysCatering(10, "A547", "6874714145", 0);
event[1] = new CarlysCatering(100, "B527", "6874874945", 2);
event[2] = new CarlysCatering(50, "C546", "6874785145", 3);
event[3] = new CarlysCatering(40, "L577", "6874321485", 1);
event[4] = new CarlysCatering(70, "A111", "6874714145", 4);
event[5] = new CarlysCatering(90, "K222", "6874974855", 2);
event[6] = new CarlysCatering(11, "F798", "6875555555", 3);
event[7] = new CarlysCatering(17, "T696", "6474763898", 0);
//SORT
int selection = 0;
do {
System.out.println("1 - sort by eventID. 2 - sort by number of guests. 3 - sort by event type. 4 - quit");
selection = input.nextInt();
input.nextLine();
if(selection == 1) {
}
if(selection == 2) {
int n = event.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (event[j].getGuests() > event[j + 1].getGuests()) {
// swap arr[j+1] and arr[i]
CarlysCatering temp = event[j];
event[j] = event[j + 1];
event[j + 1] = temp;
}
}
}
}
} while (selection != 4);
//Print totals
event[0].getTotals(); event[1].getTotals(); event[2].getTotals(); event[3].getTotals(); event[4].getTotals(); event[5].getTotals(); event[6].getTotals(); event[7].getTotals();
}
////////////////////////////////////////////////////// STATIC METHODS //////////////////////////////////////////////////////////////////////
}
public class CarlysCatering {
public static final int PRICE_PER_GUEST_HIGH = 35;
public static final int PRICE_PER_GUEST_LOW = 32;
public static final int CUTOFF_VALUE_LARGE = 49;
private int guests;
private int totalPrice;
private String eventID;
private String phoneNumber;
private String eventType;
private boolean largeEvent;
///////////////////////////////////////////////////// CONSTRUCTORS //////////////////////////////////////////////////////////////////
CarlysCatering() {
this.guests = 0;
this.eventID = "A000";
this.phoneNumber = "0000000000";
}
CarlysCatering(int guests, String eventID, String phoneNumber, int eventType) {
this.guests = guests;
this.eventID = eventID;
//Phone Number formatting
String phoneNumber2 = "";
int count = 0;
for(int i = 0; i < phoneNumber.length(); i++) {
if (Character.isDigit(phoneNumber.charAt(i))) {
phoneNumber2 += phoneNumber.charAt(i);
count += 1;
}
}
if (count != 10) {
this.phoneNumber = "0000000000";
} else {
String phoneNumber3 = "(" + phoneNumber2.substring(0,3) + ") " + phoneNumber2.substring(3,6) + "-" + phoneNumber2.substring(6,10);
this.phoneNumber = phoneNumber3;
}
//Event type formatting
final String[] eventString = new String[5];
eventString[0] = "wedding"; eventString[1] = "baptism"; eventString[2] = "birthday"; eventString[3] = "corporate"; eventString[4] = "other";
if(eventType > -1 && eventType < 5) {
this.eventType = eventString[eventType];
} else {
this.eventType = eventString[4];
}
}
///////////////////////////////////////////////////////// SETTERS AND GETTERS /////////////////////////////////////////////////
//Setters
public void setEventID(String eventID) {
this.eventID = eventID;
}
public void setGuests(int guests) {
this.guests = guests;
}
public void setPhoneNumber(String phoneNumber) {
String phoneNumber2 = "";
int count = 0;
for (int i = 0; i < phoneNumber.length(); i++) {
if (Character.isDigit(phoneNumber.charAt(i))) {
phoneNumber2 += phoneNumber.charAt(i);
count += 1;
}
}
if (count != 10) {
this.phoneNumber = "0000000000";
} else {
String phoneNumber3 = "(" + phoneNumber2.substring(0, 3) + ") " + phoneNumber2.substring(3, 6) + "-" + phoneNumber2.substring(6, 10);
this.phoneNumber = phoneNumber3;
}
}
public void setEventType(String eventType) {
this.eventType = eventType;
}
//Getters
public int getTotalPrice() {
return totalPrice;
}
public int getGuests() {
return guests;
}
public String getEventID() {
return eventID;
}
public String getPhoneNumber() {
return phoneNumber;
}
public String getEventType() {
return eventType;
}
/////////////////////////////////////////////////////// ADDITIONAL METHODS ///////////////////////////////////////////////////////////////////
public void isLargeEvent() {
if (this.guests > CUTOFF_VALUE_LARGE) {
largeEvent = true;
System.out.println("Yes this is a large event.");
} else {
largeEvent = false;
System.out.println("This is not a large event");
}
}
public void getTotals() {
boolean largeEvent = false;
if(this.guests > CUTOFF_VALUE_LARGE) {
largeEvent = true;
this.totalPrice = this.guests * PRICE_PER_GUEST_HIGH;
} else {
largeEvent = false;
this.totalPrice = this.guests * PRICE_PER_GUEST_LOW;
}
System.out.println("The number of guests attending event " + this.eventID + " " + this.eventType + " is: " + this.guests + ". The total price is $" + this.totalPrice);
System.out.println("Large event: " + largeEvent);
System.out.println("The phone number on file is " + this.phoneNumber);
}
// Static methods
public static void showMotto() {
System.out.println("*****Carly's makes the food that makes it a party.*****");
}
}
The error message I get when I try to sort by guests is Exception in thread "main" java.lang.NullPointerException and then error code exit -1. The line that's causing the error is:
if (event[j].getGuests() > event[j + 1].getGuests()) {
You create an Array with the size 100.
After that, you fill it from index 0 to 7.
Every other place of the array remains null but the length is 100.
Then, you try to sort the array.
This throws a NullPointerException when you try to dereference (access) the 8. element:
event[j+1].getGuests()
I think you should use a smaller array(size 8) or a List.

Having trouble reseting game to previous round JAVA

I made a program which asks the user for their pet name and assigns it states of mind for 5 rounds. If the pet gets too angry it is put down.
What I am having trouble with is allowing the user to restart to an earlier stage at the game before the pet died.
Compiling the code would help illustrate the issue.
Any help would be appreciated.
import java.util.Random;
import java.util.Scanner;
class dinoo {
public static void main(String[] p) {
Pet p1 = new Pet();
Pet p2 = new Pet();
Scanner scanner = new Scanner(System.in);
String petname;
String species;
String angerlevel;
int thirst;
int hunger;
int irritability;
explain();
petname = askpetname();
species = askpetspecies();
int howmanyrounds = 5;
for (int i = 0; i < howmanyrounds; i++) {
int number = i + 1;
String num = Integer.toString(number);
print("Round " + number);
String[] emotionalstate = newarray(5);
thirst = thirstlevel(p1);
hunger = hungerlevel(p1);
irritability = irritabilitylevel(p1);
angerlevel = anger(hunger, thirst, irritability);
p1 = setpetname(p1, petname);
p1 = setspecies(p1, species);
p1 = setthirst(p1, thirst);
p1 = setanger(p1, angerlevel);
p1 = sethunger(p1, hunger);
p1 = setangervalue(p1, irritability);
print(petname + "'s thirst level is " + thirst + " , hunger level is " + hunger + ", irritability level is " + irritability + " and therefore emotional state is " + angerlevel);
if (angerlevel.equals("DANGEROUS")) {
print(petname + " is looking " + angerlevel + ", get out now! we will have to put " + petname + " down.");
boolean continueEnd = petdead();
if (continueEnd == false) {
System.exit(0);
} else {
emotionalstate = wheretogo(emotionalstate[]);
}
} else if (angerlevel.equals("Serene")) {
print("He looks " + angerlevel + ". Seems in a good mood.");
} else if (angerlevel.equals("Grouchy")) {
print("You should give him a treat to cheer him up.");
}
whatdoyouwant(p1);
print("Your pets emotion is now " + anger(getthirst(p1), gethungervalue(p1), getirritabilityvalue(p1)));
emotionalstate[i] = anger(getthirst(p1), gethungervalue(p1), getirritabilityvalue(p1));
print("Emotional state " + emotionalstate[i] + " has been saved!");
}
System.exit(0);
}
public static String[] wheretogo(String[] a) {
Scanner scanner = new scanner;
print("which level would you like to return to?");
int number = scanner.nextInt();
String level = a[number];
return a;
}
public static boolean petdead() {
Scanner scanner = new Scanner(System.in);
print("Your pet has been killed. Would you like to continue? (True or False)");
boolean yesorno = scanner.nextBoolean();
return yesorno;
}
public static int inputint(String message) {
Scanner scanner = new Scanner(System.in);
System.out.println(message);
int answer = scanner.nextInt();
return answer;
}
public static String[] newarray(int arraylength) {
String[] emotionalstate = new String[arraylength];
return emotionalstate;
}
//takes input from user to cheerup/feed/sing to the animal to lower values stored in setter/getter
public static Pet whatdoyouwant(Pet p1) {
Scanner scanner = new Scanner(System.in);
print("what would you like to do to the pet? (treat/water/sing)");
String ans = scanner.nextLine();
Random ran = new Random();
int reduction = ran.nextInt(6);
if (ans.equalsIgnoreCase("treat")) {
int hunger = gethungervalue(p1) - reduction;
if (hunger < 0) {
hunger = 0;
}
p1 = sethunger(p1, hunger);
print("Your pets hunger has been reduced to:");
printint(gethungervalue(p1));
} else if (ans.equals("sing")) {
int irrit = getirritabilityvalue(p1) - reduction;
if (irrit < 0) {
irrit = 0;
}
p1 = setirritability(p1, irrit);
print("Your pets irritability hs been reduced to:");
printint(getirritabilityvalue(p1));
} else if (ans.equals("water")) {
int thirst = getthirst(p1) - reduction;
if (thirst < 0) {
thirst = 0;
}
p1 = setthirst(p1, thirst);
print("Your pets thirst is has been reduced to:");
printint(getthirst(p1));
} else {
print("That action seems to agitate your pet, try something else before your pet becomes dangerous!");
}
return p1;
}
//GETTER METHOD
public static String getpetname(Pet p) {
return p.name;
}
public static String getspecies(Pet p) {
return p.species;
}
public static String getanger(Pet p) {
return p.anger;
}
public static int getthirst(Pet p) {
return p.thirst;
}
public static int gethungervalue(Pet p) {
return p.hunger;
}
public static int getangervalue(Pet p) {
return p.angervalue;
}
public static int getirritabilityvalue(Pet p) {
return p.irritability;
}
//SETTER METHOD
public static Pet setangervalue(Pet p, int whatsangervalue) {
p.angervalue = whatsangervalue;
return p;
}
public static Pet setpetname(Pet p, String name) {
p.name = name;
return p;
}
public static Pet setspecies(Pet p, String petspecies) {
p.species = petspecies;
return p;
}
public static Pet setanger(Pet p, String howangry) {
p.anger = howangry;
return p;
}
public static Pet sethunger(Pet p, int howhungry) {
p.hunger = howhungry;
return p;
}
public static Pet setthirst(Pet p, int howthirsty) {
p.thirst = howthirsty;
return p;
}
public static Pet setirritability(Pet p, int howirritable) {
p.irritability = howirritable;
return p;
}
//Method printing out statement to explain functionality of program
public static void explain() {
print("The following program demonstrates use of user input by asking for pet name.");
return;
}
//Method to ask the pet name
public static String askpetname() {
Scanner scanner = new Scanner(System.in);
print("Name your dinosaur pet!");
String petname = scanner.nextLine();
return petname;
}
//Method to ask the pet species
public static String askpetspecies() {
Scanner scanner = new Scanner(System.in);
print("What species is your pet?");
String petspecies = scanner.nextLine();
return petspecies;
}
//Randomly allocates thirst value 0-10
public static int thirstlevel(Pet p1) {
Random ran = new Random();
int thirst = ran.nextInt(11);
setthirst(p1, thirst);
return thirst;
}
//Randomly Allocates hunger value 0-10
public static int hungerlevel(Pet p1) {
Random ran = new Random();
int hunger = ran.nextInt(11);
sethunger(p1, hunger);
return hunger;
}
//randomly generates a irratibilty value
public static int irritabilitylevel(Pet p1) {
Random ran = new Random();
int irritable = ran.nextInt(11);
setirritability(p1, irritable);
return irritable;
}
//Method calculates the anger value based on the thirst/hunger/irritability average
public static String anger(int thirst, int hunger, int irritability) {
int angerscore = (thirst + hunger + irritability) / 3;
String temper;
temper = Integer.toString(angerscore);
if (angerscore <= 1) {
temper = "Serene";
} else if (angerscore <= 3) {
temper = "Grouchy";
} else if (5 < angerscore) {
temper = "DANGEROUS";
}
return temper;
}
//HELPER PRINT METHOD
public static String print(String message) {
System.out.println(message);
return message;
}
public static int printint(int message) {
System.out.println(message);
return message;
}
}//END class dinoo
class Pet {
String name;
String species;
int thirst;
int hunger;
String anger;
int irritability;
int angervalue;
} //END class pet
First of all you should look at the compile errors in your code before submitting a question here.
Please read the links provided in the comments to learn how to submit a proper question.
I tried to compile your code and it had the following errors:
java2.java:51: error: '.class' expected
emotionalstate = wheretogo(emotionalstate[]);
^
java2.java:75: error: '(' or '[' expected
Scanner scanner = new scanner;
That means in line 51, you're passing emotionalstate[] , which is emotional state array, whereas emotionalstate itself is an array, so you're passing an array of an array.
So just change it to emotionalstate = wheretogo(emotionalstate)
And in line 75, your initialization of Scanner object is wrong, change it to Scanner scanner = new Scanner();

Cannot add items to Shopping Cart object array (Java) [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 6 years ago.
In my ShoppingCart class, I am unable to add orders to my newCart object array using the method add(). Instead I am getting the following errors:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at ShoppingCart.add(ShoppingCart.java:25)
at ShoppingCart.main(ShoppingCart.java:99)
I cannot think of a way to assess whether elements have been inserted into my array or not and where exactly the array index is wrong.
Should I declare the new ShoppingCart object inside of the add() method? At the moment, I am using main() to test the methods.
This is my IceCreamOrder class:
import java.util.Scanner; //Used to read user input from keyboard
import java.text.DecimalFormat; //Used to format output of decimal values
public class IceCreamOrder
{
//Private instance variable declarations
private String flavor;
private String vessel;
private String amount;
private double unitPrice;
private int quantity;
//Constructor declarations
public IceCreamOrder(String flavor, String vessel, String amount, double unitPrice, int quantity)
{
this.flavor = flavor;
this.vessel = vessel;
this.amount = amount;
this.unitPrice = unitPrice;
this.quantity = quantity;
}
public IceCreamOrder(String flavor, String vessel, String amount, double unitPrice)
{
this.flavor = flavor;
this.vessel = vessel;
this.amount = amount;
this.unitPrice = unitPrice;
this.quantity = 1;
}
public IceCreamOrder()
{
this.flavor = "";
this.vessel = "";
this.amount = "";
this.unitPrice = 0.0;
this.quantity = 0;
}
//Calculates the total price of order
public double price()
{
return quantity * unitPrice;
}
//Accessor method declarations
public String getFlavor()
{
return flavor;
}
public String getVessel()
{
return vessel;
}
public String getAmount()
{
return amount;
}
public double getUnitPrice()
{
return unitPrice;
}
public int getQuantity()
{
return quantity;
}
//Mutator method declarations
public void setFlavor(String flavor)
{
this.flavor = flavor;
}
public void setVessel(String vessel)
{
this.vessel = vessel;
}
public void setAmount(String amount)
{
this.amount = amount;
}
public void setUnitPrice(double unitPrice)
{
this.unitPrice = unitPrice;
}
public void setQuantity(int quantity)
{
this.quantity = quantity;
}
//toString method declaration
public String toString()
{
DecimalFormat pattern0dot00 = new DecimalFormat("$0.00");
return (((getQuantity() == 1) ? (getQuantity() + " order") : (getQuantity() + " orders")) + " of " +
getAmount() + " of " + getFlavor() + " ice cream in a " + getVessel() + " for " +
pattern0dot00.format(price()) + " = " + getQuantity() + " x " + getUnitPrice());
}
public static void main(String[] args)
{
//Object declarations
IceCreamOrder newOrder = new IceCreamOrder();
Scanner keyboard = new Scanner(System.in);
//Array declarations
String[] flavorList = {"Avocado", "Banana", "Chocolate", "Hazelnut", "Lemon", "Mango", "Mocha", "Vanilla"};
String[] vesselList = {"Cone", "Cup", "Sundae"};
String[] amountList = {"Single Scoop", "Double Scoop", "Triple Scoop"};
String[] quantityList = {"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten"};
System.out.println("Placing an order is as easy as ABC, and D.");
System.out.println("Step A: Select your favorite flavour");
String outputFlavor = "";
for (int i = 1; i <= flavorList.length; i++)
{
outputFlavor = " (" + i + ") " + flavorList[i-1];
System.out.println(outputFlavor);
}
System.out.print("?-> Enter an option number: ");
int inputFlavor = keyboard.nextInt();
String flavorString = "";
switch (inputFlavor)
{
case 1:
flavorString = flavorList[0];
break;
case 2:
flavorString = flavorList[1];
break;
case 3:
flavorString = flavorList[2];
break;
case 4:
flavorString = flavorList[3];
break;
case 5:
flavorString = flavorList[4];
break;
case 6:
flavorString = flavorList[5];
break;
case 7:
flavorString = flavorList[6];
break;
case 8:
flavorString = flavorList[7];
break;
}
newOrder.setFlavor(flavorString);
System.out.println();
System.out.println("Step B: Select a vessel for your ice cream:");
String outputVessel = "";
for (int i = 1; i <= vesselList.length; i++)
{
outputVessel = " (" + i + ") " + vesselList[i-1];
System.out.println(outputVessel);
}
System.out.print("?-> Enter an option number: ");
int inputVessel = keyboard.nextInt();
String vesselString = "";
switch (inputVessel)
{
case 1:
vesselString = vesselList[0];
break;
case 2:
vesselString = vesselList[1];
break;
case 3:
vesselString = vesselList[2];
break;
}
newOrder.setVessel(vesselString);
System.out.println();
System.out.println("Step C: How much ice cream?");
String outputAmount = "";
for (int i = 1; i <= amountList.length; i++)
{
outputAmount = " (" + i + ") " + amountList[i-1];
System.out.println(outputAmount);
}
System.out.print("?-> Enter an option number: ");
int inputAmount = keyboard.nextInt();
String amountString = "";
switch (inputAmount)
{
case 1:
amountString = amountList[0];
break;
case 2:
amountString = amountList[1];
break;
case 3:
amountString = amountList[2];
break;
}
newOrder.setAmount(amountString);
System.out.println();
System.out.println("Step D: How many orders of your current selection?");
String outputQuantity = "";
for (int i = 1; i <= quantityList.length; i++)
{
outputQuantity = " (" + i + ") " + quantityList[i-1];
System.out.println(outputQuantity);
}
System.out.print("?-> Enter how many orders: ");
int inputQuantity = keyboard.nextInt();
newOrder.setQuantity(inputQuantity);
System.out.println();
if (newOrder.getAmount() == amountList[0])
{
if (newOrder.getVessel() == vesselList[0])
{
newOrder.setUnitPrice(2.99);
}
else if (newOrder.getVessel() == vesselList[1])
{
newOrder.setUnitPrice(3.49);
}
else
{
newOrder.setUnitPrice(4.25);
}
}
else if (newOrder.getAmount() == amountList[1])
{
if (newOrder.getVessel() == vesselList[0])
{
newOrder.setUnitPrice(3.99);
}
else if (newOrder.getVessel() == vesselList[1])
{
newOrder.setUnitPrice(4.49);
}
else
{
newOrder.setUnitPrice(5.25);
}
}
else
{
if (newOrder.getVessel() == vesselList[0])
{
newOrder.setUnitPrice(4.99);
}
else if (newOrder.getVessel() == vesselList[1])
{
newOrder.setUnitPrice(5.49);
}
else
{
newOrder.setUnitPrice(6.25);
}
}
System.out.println(newOrder);
}
}
This is my ShoppingCart class:
public class ShoppingCart
{
private IceCreamOrder[] shoppingCart;
private int maxQuantity;
private int orderTracker;
//Constructor declarations
public ShoppingCart()
{
this.shoppingCart = new IceCreamOrder[maxQuantity];
this.maxQuantity = 5;
this.orderTracker = 1;
}
public void add(IceCreamOrder order)
{
if (orderTracker > maxQuantity)
{
System.out.println("Shopping cart is full.");
}
else
{
shoppingCart[orderTracker - 1] = order;
orderTracker++;
}
}
//Method determines if shopping cart is empty
public boolean isEmpty()
{
int orderCount = 0;
for (int i = 0; i < shoppingCart.length; i++)
{
if (shoppingCart[i] != null)
{
orderCount++;
}
}
return ((orderCount == 0) ? true : false);
}
//Method determines if shopping cart is full
public boolean isFull()
{
int orderCount = 0;
for (int i = 0; i < shoppingCart.length; i++)
{
if (shoppingCart[i] != null)
{
orderCount++;
}
}
return ((orderCount == maxQuantity) ? true : false);
}
public IceCreamOrder get(int position)
{
return shoppingCart[position-1];
}
//Method determines the number of orders currently in shopping cart
public int size()
{
int orderCount = 0;
for (int i = 0; i < shoppingCart.length; i++)
{
if (shoppingCart[i] != null)
{
orderCount++;
}
}
return orderCount;
}
public static void main(String[] args)
{
ShoppingCart newCart = new ShoppingCart();
IceCreamOrder firstOrder = new IceCreamOrder("Vanilla", "Cone", "Single Scoop", 2.99);
IceCreamOrder secondOrder = new IceCreamOrder("Vanilla", "Cone", "Single Scoop", 2.99);
IceCreamOrder thirdOrder = new IceCreamOrder("Vanilla", "Cone", "Single Scoop", 2.99);
IceCreamOrder fourthOrder = new IceCreamOrder("Vanilla", "Cone", "Single Scoop", 2.99);
IceCreamOrder fifthOrder = new IceCreamOrder("Vanilla", "Cone", "Single Scoop", 2.99);
//IceCreamOrder sixthOrder = new IceCreamOrder("Vanilla", "Cone", "Single Scoop", 2.99);
newCart.add(firstOrder);
newCart.add(secondOrder);
newCart.add(thirdOrder);
newCart.add(fourthOrder);
newCart.add(fifthOrder);
//newCart.add(sixthOrder);*/
System.out.println(newCart.size());
System.out.println(firstOrder);
System.out.println(newCart.isEmpty());
System.out.println(newCart.isFull());
}
}
the problem is in this two lines
this.shoppingCart = new IceCreamOrder[maxQuantity];
this.maxQuantity = 5;
this intialize shoppingCart Array with zero length that cause the exception
you need to change the order of ther like this
this.maxQuantity = 5;
this.shoppingCart = new IceCreamOrder[maxQuantity];

Categories

Resources