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];
Related
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
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();
}
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.
public abstract class Character{
public enum Type{ ROGUE, PALADIN, JACKIE_CHEN, SKELETON, GOBLIN, WIZARD}
private String name;
private int hitPoints;
private int strength;
private Weapon weapon;
//other attributes
//methods
public Character(Type characterType){
switch(characterType){
case ROGUE:
//set the attributes for a Rogue
name = "Rogue";
// TODO: set other attributes
hitPoints = 55;
strength = 8;
Weapon rogue = new Weapon("Short Sword", 1, 4);
break;
case PALADIN:
//set the attributes for a Rogue
name = "Paladin";
// TODO: set other attributes
hitPoints = 35;
strength = 14;
Weapon paladin = new Weapon("Long Sword",3,7);
break;
case JACKIE_CHEN:
name = "Jackie Chen";
hitPoints =45;
strength = 10;
Weapon jackie = new Weapon("Jump Kick",2, 6);
break;
case SKELETON:
name = "Skeleton";
hitPoints = 25;
strength = 3;
Weapon skeleton = new Weapon("Short Sword" ,1, 4);
break;
case GOBLIN:
name = "Goblin";
hitPoints = 25;
strength = 4;
Weapon goblin = new Weapon("Axe",2,6);
break;
case WIZARD:
name = "Wizard";
hitPoints = 40;
strength = 8;
Weapon wizard = new Weapon("Fire Blast", 4, 10);
break;
}
}
public String getName(){
return name;
}
public int getHitPoints(){
return hitPoints;
}
public int getStrength(){
return strength;
}
public void setStrength(int _strength){
this.strength =_strength;
}
public void setWeapon(Weapon _weapon){
this.weapon = _weapon;
}
public void attack(){
}
public void increaseHitPoints(){
}
public void decreaseHitPoints(){
}
/*public boolean isDefeated(){
}*/
}
import java.util.Scanner;
import java.util.Random;
public class Player extends Character{
// attributes for the plauer class
// initilizes the fields
private int coins;
private Potion[] inventory;
Random randomNums = new Random();
Scanner keyboard = new Scanner(System.in);
//methods
public Player(Type playerType){
super(playerType);
coins = 0;
inventory = new Potion[5];
}
public void increaseStrength(int strengthIncrease){
enemy.getHitPoints() -= playerATK;
}
public int getCoins(){
return coins;
}
public void increaseCoins(int coins){
}
public void decreaseCoins(int coins){
}
public void addToInventory(String a, Type potion){
}
public void removeFromInventory(int index){
}
public void displayInventory(){
}
/*public int getNumOpenSlots(){
return numOpenSlots;
}*/
public void battleMinion(Enemy enemy){
Enemy goblin = new Enemy(Character.Type.GOBLIN);
int playerDamage =0, playerATK =0, enemyATK =0, enemyDamage =0;
if (enemy.getName() == "Goblin" && getName()=="Rogue"){
for (int i = 1; i <= goblin.getNumGoblins(); i++)
{
System.out.printf("***%s vs %s %d***\n", getName(), enemy.getName(), i);
while(enemy.getHitPoints() > 0 && getHitPoints() > 0)
{
playerDamage = randomNums.nextInt(Weapon.SHORT_SWORD_MAX - Weapon.SHORT_SWORD_MIN + 1) + Weapon.SHORT_SWORD_MIN;
playerATK = getStrength() + playerDamage;
enemy.getHitPoints() -= playerATK;
System.out.printf("%s attacks with ATK = %d + %d = %d\n", getName(), getStrength(), playerDamage, playerATK);
System.out.printf("%s HP is now %d - %d = %d\n\n", enemy.getName(), enemy.getHitPoints() + playerATK, playerATK, enemy.getHitPoints());
if (enemy.getHitPoints() <= 0)
break;
enemyDamage = randomNums.nextInt(Weapon.AXE_MAX - Weapon.AXE_MIN + 1) + Weapon.AXE_MAX;
enemyATK = enemy.getStrength() + enemyDamage;
getHitPoints() -= enemyATK;
System.out.printf("%s attacks with ATK = %d + %d = %d\n", getName(), enemy.getStrength(), enemyDamage, enemyATK);
System.out.printf("%s HP is now %d - %d = %d\n\n", getName(), getHitPoints() + enemyATK, enemyATK, getHitPoints());
} // end of while loop
if (getHitPoints() > 0){
System.out.printf("%s defeated %s %d!\n\n", getName(), enemy.getName(), i);
coins = randomNums.nextInt((50 - 30) + 1) + 30;
System.out.println(getName() + " gains " + coins + " gold coins!\n");
//player[4] += coins;
}
else
{
System.out.printf("--%s is defeated in battle!--\n\nGAME OVER\n", getName());
System.exit(0);
}
if(i <= goblin.getNumGoblins() - 1){
System.out.println("Press enter to continue...");
keyboard.nextLine();
}
}
}
Error is as follows
./Player.java:59: error: unexpected type
enemy.getHitPoints() -= playerATK;
^
required: variable
found: value
./Player.java:68: error: unexpected type
getHitPoints() -= enemyATK;
I know this is wrong, but what is the reason behind this? Also I have
public void increaseHitPoints(){
}
public void decreaseHitPoints(){
}
these two class in my character class, I don't how to code to make this work.
getHitPoints() is a method that returns a value. You can't assign anything to that expression, and the -= operator performs both subtraction and assignment.
Instead of
getHitPoints() -= playerATK;
write
setHitPoints (getHitPoints() - playerATK);
or
decreaseHitPointsBy (playerATK); // this approach would require a corresponding
// increaseHitPointsBy (value) method
I'm trying to use insertion sort to sort for the batting average of the players. I get an error message "The method get(int) in the type java.util.ArrayList is not applicable for the arguments (double)" on the lines of S.get(outer) and S.get(inner - 1)
What am I doing wrong?
How can I fix this?
import java.util.*;
import java.io.*;
class menu {
public static void main (String [] arg) throws IOException
{
PlayerRip.PlayerInfo obj5 = new PlayerRip.PlayerInfo();
ArrayList<Player> obj6 = new ArrayList<Player>();
MainMenu(obj5, obj6);
}
public static void MainMenu(PlayerRip P, ArrayList<Player> S) throws IOException
{
Scanner keyboard = new Scanner(System.in);
int response = 0;
int response2 = 0;
ArrayList<Player> obj1 = new ArrayList<Player>();
obj1.add(new Player("Agostini", "Aldo", "Pitcher", 170, 20, 72, 12, 6, 1, 1, 0));
do
{
System.out.println("1. Open A file:");
System.out.println("7. Exit the program");
response = keyboard.nextInt();
switch (response)
{
case 1:
{
openFile(obj1);
do
{
System.out.println("2. Display all players");
System.out.println("3. Enter player's Height");
System.out.println("4. Sort all players alphabetically by Surname");
System.out.println("5. Sort all players by batting average");
System.out.println("6. Delete a player by selecting the player's surname from a list");
System.out.println("7. Add a player to the stats");
System.out.println("8. Save stats to a file");
System.out.println("9. Exit the program");
response2 = keyboard.nextInt();
switch (response2)
{
case 2:
{
displayInfo(obj1);
break;
}
case 3:
{
changeHeight(obj1);
break;
}
case 4:
{
BubbleSort(obj1);
break;
}
case 5:
{
break;
}
case 6:
{
deletePlayerInfo(obj1);
break;
}
case 7:
{
addPlayerInfo(obj1);
break;
}
case 8:
{
saveFile(obj1);
break;
}
case 9:
{
System.exit(0);
break;
}
}
} while (response2 != 9);
break;
}
case 7:
{
System.exit(0);
break;
}
}
} while (response != 1 || response != 7); // End of switch statement
}
public static void displayInfo(ArrayList<Player> S) {
System.out.printf("%10s %10s %10s \t %4s %4s \t %4s \t %4s %4s \t %4s %4s %4s \n", "Surname", "GivenName", "Postition", "Height(cm)", "Hits", "AtBats", "Singles", "Doubles", "Triples", "HomeRuns", "Batting Average");
for (int index = 0; index < S.size(); index++)
S.get(index).displayInfo();
}
public static void openFile(ArrayList<Player> S) throws IOException // This method allows the oepning of files into the program
{
Scanner userInput = new Scanner(System.in);
String fileName;
S.removeAll(S); // Empties the list readies it for a new oned
System.out.println("Enter a file name to open: ");
fileName = userInput.next().trim();
File file = new File(fileName);
if (file.exists()) // Checks whether or not the file exists in the directory
{
Scanner fileInput = new Scanner(file);
while (fileInput.hasNext())
{
S.add(new Player(fileInput.next(), fileInput.next(), fileInput.next(), fileInput.nextInt(), fileInput.nextInt(), fileInput.nextInt(), fileInput.nextInt(), fileInput.nextInt(), fileInput.nextInt(), fileInput.nextInt(), fileInput.nextDouble())); // If it exists it adds the token values into the respective lists
}
fileInput.close(); // Closes further file input
}
else // Error message incase the file-name is not valid
System.out.println("FILE NOT FOUND");
}
public static void saveFile(ArrayList<Player> S) throws IOException // This method allows for the saving of values to an external file
{
Scanner inputInfo = new Scanner(System.in);
String fileName;
System.out.println("Enter a file name to save the info with:");
fileName = inputInfo.next().trim();
File file = new File(fileName);
PrintStream writeFile = new PrintStream(file);
for (int i = 0; i < S.size(); i++) // Gathers all values and prints them to the file in their respective format
{
writeFile.print(S.get(i).getName() + " ");
writeFile.print(S.get(i).getName2() + " ");
writeFile.print(S.get(i).getPosition() + " ");
for (int j = 0; j < 7; j++)
writeFile.print(S.get(i).getMark(j) + " ");
for (int j = 0; j < 1; j++)
writeFile.print(S.get(i).getBatAvg(j));
writeFile.println(" ");
}
writeFile.close(); // Stops any further writing to the file
}
public static void deletePlayerInfo(ArrayList<Player> S) // THis method allows the user to delete any player within the list
{
int deleteIt = 0;
Scanner keyboard = new Scanner(System.in);
System.out.println("Please select the number of the player to be deleted: ");
for (int i = 0; i < S.size(); i++) // Displays only the first/surNames of the players
{
System.out.print(i + ". " + S.get(i).getName());
System.out.println(" ");
}
deleteIt = keyboard.nextInt();
S.remove(deleteIt);
}
public static void addPlayerInfo(ArrayList<Player> S) // This method allows the user to add a new player to the list
{
String firstName = "";
String surName = "";
String posName = "";
int heightVal = 0;
int hitsVal = 0;
int atBatsVal = 0;
int singVal = 0;
int doubVal = 0;
int tripVal = 0;
int homeVal = 0;
Scanner keyboard = new Scanner(System.in); // Various user input
System.out.println("Enter the surname and name of the new player: ");
System.out.println("Surname: ");
surName = keyboard.nextLine();
System.out.println("Name: ");
firstName = keyboard.nextLine();
System.out.println("Enter the position of the new player: ");
System.out.println("Position: ");
posName = keyboard.nextLine();
System.out.println("Enter the height of the new player: ");
heightVal = keyboard.nextInt();
System.out.println("Enter the batting statistics: ");
System.out.println("Hits: ");
hitsVal = keyboard.nextInt();
System.out.println("AtBats: ");
atBatsVal = keyboard.nextInt();
System.out.println("Singles: ");
singVal = keyboard.nextInt();
System.out.println("Doubles: ");
doubVal = keyboard.nextInt();
System.out.println("Triples: ");
tripVal = keyboard.nextInt();
System.out.println("HomeRuns: ");
homeVal = keyboard.nextInt();
S.add(new Player(surName, firstName, posName, heightVal, hitsVal, atBatsVal, singVal, doubVal, tripVal, homeVal, 0));
}
public static void changeHeight(ArrayList<Player> S)
{
int playerSel = 0;
int newHeight = 0;
Scanner keyboard = new Scanner(System.in); // Various user input
System.out.println("Select a player to enter the height for: ");
do
{
for (int i = 0; i < S.size(); i++) // Displays only the first/surNames of the players
{
System.out.print(i + ". " + S.get(i).getName());
System.out.println(" ");
}
playerSel = keyboard.nextInt();
System.out.println("Enter the height for this character: ");
newHeight = keyboard.nextInt();
if (newHeight < 125 && newHeight > 240)
{
System.out.println("WRONG! TRY AGAIN!");
}
else
{
}
} while (newHeight >= 125 && newHeight <= 240);
}
public static void BubbleSort(ArrayList<Player> S){
Player strTemp;
int i = 0;
boolean isSorted = false;
while(i < S.size()&&isSorted==false)
{
isSorted = true;
for(int j = 0; j < (S.size()-1)-i;j++)
{
if(S.get(j).getName().compareToIgnoreCase(S.get(j+1).getName())>0){
strTemp = S.get(j);
S.set(j,S.get(j+1));
S.set(j+1,strTemp);
isSorted = false;
}
}
i++;}
}
public static void InsertionSort(ArrayList<Player> S){ // hits over atbats
int outer;
double inner;
for(outer = 1; outer < S.size();outer++){
double keyItem = S.get(outer).getBatAvg();
inner = outer - 1 ;
while(inner >0&&S.get(inner-1).getBatAvg() > keyItem){
S.set((inner),S.get(inner-1));
inner--;
break;
}
double helpSort = S.get(inner).getBatAvg();
helpSort = keyItem;
}
}
}
class PlayerRip {
public String name;
public String name2;
public String position;
public int [ ] mark = new int[7];
public double [ ] batAvg = new double[1];
static class PlayerInfo extends PlayerRip
{
PlayerInfo() {
this.name = "-1";
this.name2 = "-1";
this.position = "-1";
for (int i=0; i < mark.length; i++)
mark[i] = -1;
}
PlayerInfo(String nam, String nam2, String pos, int a, int b, int c, int d, int e, int f, int g, double h) {
this.name = nam;
this.name2 = nam2;
this.position = pos;
this.mark[0] = a; this.mark[1] = b; this.mark[2] = c; this.mark[3] = d; this.mark[4] = e; this.mark[5] = f; this.mark[6] = g;
batAvg[0] = (((double)mark[1] / (double)mark[2]) * 100);
}
public void setName(String nam) { name = nam; }
public void setName2(String nam2) { name2 = nam2; }
public void setPosition(String pos) { position = pos; }
public void setMark(int index, int mark) { this.mark[index] = mark; }
public void setBatAvg(int index, double batAvg) {this.batAvg[index] = batAvg;}
public String getName() { return this.name; }
public String getName2() { return this.name2; }
public String getPosition() { return this.position; }
public double getBatAvg() { return this.batAvg[0];}
public int getMark(int index) { return this.mark[index]; }
public void setHeight(int index, int mark) { this.mark[index] = mark; }
public int getHeight(int index) { return this.mark[0]; }
public void setHits (int index, int mark) { this.mark [index] = mark; }
public int getHits (int index) { return this.mark [1]; }
public void setAtBats (int index, int mark) { this.mark [index] = mark; }
public int getAtBats(int index) { return this.mark [2]; }
public void setSingles (int index, int mark) { this.mark [index] = mark; }
public int getSingles (int index) { return this.mark [3] ; }
public void setDoubles (int index, int mark) { this.mark [index] = mark; }
public int getDoubles (int index) { return this.mark [4] ; }
public void setTriples (int index, int mark) { this.mark [index] = mark; }
public int getTriples (int index) { return this.mark [5] ; }
public void setHomeRuns (int index, int mark) { this.mark [index] = mark; }
public int getHomeRuns (int index) { return this.mark [6] ; }
}
}
sorry for format im new to the site
}
public static void InsertionSort(ArrayList<Player> S){ // hits over atbats
int outer;
double inner;
for(outer = 1; outer < S.size();outer++){
double keyItem = S.get(outer).getBatAvg();
inner = outer - 1 ;
while(inner >0&&S.get(inner-1).getBatAvg() > keyItem){
S.set((inner),S.get(inner-1));
inner--;
break;
}
double helpSort = S.get(inner).getBatAvg();
helpSort = keyItem;
}
}
}
is the specific area of problems
S.get() and S.set() take a int variable so cast inner to a int.
You defined inner as a double, and in Java, when you do math with a double and an int (such as inner - 1), you'll get a double as a result. This page has a fairly good explanation.
Then when you say S.get(inner - 1), you're saying to use a double as an the index in the ArrayList. The documentation for ArrayList.get says that you can only use an int as an index, and that's why you're getting a compiler error. You're also only allowed to use an int as the index for set, so that's why the compiler would complain about S.set(inner, ...).
You could just cast inner to an int, but it would be much better to declare it as an int in the first place since there's no reason it needs to be a double.