I have searched and found a few responses that didn't seem to help and I am stuck with an nullPointerException error. Below is my code the error is in my logResponse() method, any help is much appreciated.
import java.util.*;
public class Survey21 {
private Scanner in = new Scanner(System.in);
private String surveyTitle;
private static int rID;
private static int respondentID;
private int[][] responses;
//Constructors
// Default Constructor
Survey21() {
surveyTitle = "Customer Survey";
}
// Overloaded Constructor 1
Survey21(String title, int rID) {
surveyTitle = title;
rID = 0;
generateRespondentId();
}
Survey21(int[][] surveyArray) {
responses = surveyArray; // store responses
}
public static int getrID() {
return rID;
}
public static void setRespondentID(int respondentID) {
respondentID = rID;
}
public String getTitle() {
return surveyTitle;
}
public void setTitle(String title) {
surveyTitle = title;
}
public static int generateRespondentId() {
rID = ++respondentID;
return rID;
}
// displays name of survey and entire grid of results
public void displaySurveyResults() {
System.out.printf("%s\n\n", getTitle());
logResponse();
}
// dispalys question number and results for that question so far
public void displayQuestionStats(int questionNumber) {
}
// enter questions and store in an array of Strings
public void enterQuestions() {
/*String[] questions = {
"How would you rate your online shopping experience?",
"How satisfied was you with the purchase price?",
"Overall how was the online checkout experience?",
"How likely are you to recommend your friends and family to our store?",
"How concerned are you with online credit card security?",
"How likely are you to prefer a retail location compared to an online store?",
};*/
String questions[] = new String[10];
for (int i = 0; i < questions.length; i++) {
System.out.println("Please enter a question!");
questions[i] = in.nextLine();
}
/*TEST TEST***
System.out.print(questions[0] + "\n");
System.out.print(questions[1] + "\n");
System.out.print(questions[2] + "\n");
System.out.print(questions[3] + "\n");
System.out.print(questions[4] + "\n");
System.out.print(questions[5] + "\n");
System.out.print(questions[6] + "\n");
System.out.print(questions[7] + "\n");
System.out.print(questions[8] + "\n");
System.out.print(questions[9] + "\n");
*/
}
**// enters the response in the correct grid
public void logResponse() {
System.out.println("The responses are:\n");
System.out.print(" "); // align column heads
// create a column heading for each question
for (int qNumber = 0; qNumber < responses[0].length; qNumber++) {
System.out.printf("Question number %d ", qNumber + 1);
System.out.println("Response"); // column heading
}
for (int response = 0; response < responses.length; response++) {
System.out.printf("Response %2d", response + 1);
for (int qNumber : responses[response])// output responses
{
System.out.printf("%8d", qNumber);
}
}
}**
}
Probably you want the length of your array and not the length of your first element:
for (int qNumber = 0; qNumber < responses.length; qNumber++) {
System.out.printf("Question number %d ", qNumber + 1);
System.out.println("Response"); // column heading
}
I didn't initialize my array properly I did
private int[][] responses;
and it should have been
private int[][] responses = new int[5][11];
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 am struggling with an actually very easy task, which is print out items from an item array like:
arr[3,4,2,5]
0 items (0 kg)
0 items (1 kg)
0 items (2 kg)
and so on.
This is what I have done, but my program will not print anything :( Heeelp me please.
import java.util.ArrayList;
import java.util.Arrays;
public class Suitcase {
private ArrayList<Item> items = new ArrayList<>();
private final int maxWeight;
private int[] arr = new int[items.size()];
public Suitcase(int maxWeight) {
this.maxWeight = maxWeight;
}
public void addItem(Item item) {
int itemsWeight = 0;
for(Item i: items){
itemsWeight += i.getWeight();
}
if(itemsWeight + item.getWeight() <= this.maxWeight){
items.add(item);
}
}
public void array() {
for(Item item: items){
int index = item.getWeight();
this.arr[index] += 1;
}
}
public String toString() {
String returnValue = "";
for(int i = 0; i < arr.length; i++){
returnValue = arr[i] + " items " + i + " kg";
}
return returnValue;
}
}
public class Item {
private int weight;
private String name;
public Item(String name, int weight) {
this.name = name;
this.weight = weight;
}
public String getName() {
return this.name;
}
public int getWeight() {
return this.weight;
}
public String toString() {
return this.name + "(" + String.valueOf(this.weight) + ")";
}
}
Here is my main class, but it will not print anything:
public class Main {
public static void main(String[] args) {
Item book = new Item("Lord of the rings", 2);
Item phone = new Item("Nokia 3210", 1);
Item brick = new Item("brick", 4);
Suitcase suitcase = new Suitcase(5);
System.out.println(suitcase.toString());
suitcase.addItem(book);
System.out.println(suitcase);
suitcase.addItem(phone);
System.out.println(suitcase);
suitcase.addItem(brick);
System.out.println(suitcase);
}
}
Notes:
You do not need to call suitcase.toString() while printing the suitcase object. When System.out.println(suitcase); is implicitly gets converted into System.out.println(suitcase.toString());.
You can make your design simpler by having a variable to keep track of the total weight in the suitcase. Also, create a variable in Item to keep track of item's count in the suitcase.
You do not need int[] arr. It is simply adding unwanted complexity. Remove it.
It is better to use enhanced for loop if you can do so.
Given below is the code incorporating the points mentioned above:
import java.util.ArrayList;
class Suitcase {
private ArrayList<Item> items = new ArrayList<>();
private final int maxWeight;
private int totalWeight;
public Suitcase(int maxWeight) {
this.maxWeight = maxWeight;
}
public void addItem(Item item) {
if (totalWeight + item.getWeight() <= maxWeight) {
int index = items.indexOf(item);
if (index == -1) {// It means the item does not exist in the suitcase
items.add(item);
}
// If the item already exists, do not add it's entry again; just update its
// count and the totalWeight of the suitcase
totalWeight += item.getWeight();
item.setCount(item.getCount() + 1);
System.out.println(item.getName() + " was added in the suitcase");
} else {
System.out.println(item.getName() + " can not be accommodated in the suitcase.");
}
}
public String toString() {
String returnValue = "";
for (Item item : items) {
returnValue += "No. of " + item.getName() + " in the suitcase = " + item.getCount()
+ ", its total weight = " + item.getCount() * item.getWeight() + "kg\n";
}
if (returnValue.isEmpty()) {
returnValue = "The suitcase is empty.";
} else {
returnValue += "Total weight of the suitcase = " + totalWeight + "kg";
}
return returnValue;
}
}
class Item {
private int weight;
private String name;
private int count;
public Item(String name, int weight) {
this.name = name;
this.weight = weight;
}
public String getName() {
return this.name;
}
public int getWeight() {
return this.weight;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
#Override
public String toString() {
return "Item [weight=" + weight + ", name=" + name + ", count=" + count + "]";
}
}
public class Main {
public static void main(String[] args) {
Item book = new Item("Lord of the rings", 2);
Item phone = new Item("Nokia 3210", 1);
Item brick = new Item("brick", 4);
Suitcase suitcase = new Suitcase(5);
System.out.println(suitcase);
suitcase.addItem(book);
suitcase.addItem(phone);
suitcase.addItem(brick);
suitcase.addItem(phone);
suitcase.addItem(book);
System.out.println(suitcase);
}
}
Output:
The suitcase is empty.
Lord of the rings was added in the suitcase
Nokia 3210 was added in the suitcase
brick can not be accommodated in the suitcase.
Nokia 3210 was added in the suitcase
Lord of the rings can not be accommodated in the suitcase.
No. of Lord of the rings in the suitcase = 1, its total weight = 2kg
No. of Nokia 3210 in the suitcase = 2, its total weight = 2kg
Total weight of the suitcase = 4kg
Make sure to change your "toString()" function, currently it is only printing the last value, change it to:
public String toString(){
String returnValue ="";
for(int i = 0; i<arr.length;i++ ){
returnValue += arr[i] + " items " +i+" kg"; //notice its '+='
}
return returnValue;
}
You initialize your arr with value 0. Note that the initial size of new ArrayList() is 0. Take a look at this example:
import java.util.ArrayList;
class Main {
private static ArrayList<Object> items = new ArrayList();
private static int[] arr = new int[items.size()];
public static void main(String[] args) {
System.out.println(items.size()); # => 0
System.out.println(arr.length); # => 0
}
}
As a result when you call System.out.println(suitcase) the for loop in Suitcase's toString() method iterates over exactly 0 elements - therefore not outputting anything.
I am new to Java programming. I developed a Pizza class that takes for parameters and outputs the description and cost. I developed a PizzaOrderArray class that stores the pizza orders in an array. I have a class containing the main method also.
When I tried to print the values of the orders, nothing prints yet debugging shows that the proper methods and loops were entered.
What am I doing incorrect? I have invested many hours and am still very confused. Any suggestions, please? Thank you! I appreciate it.
Pizza.java
import java.text.NumberFormat;
import java.util.Locale;
public class Pizza {
public Pizza(String size, int numCheeseTop, int numPepTop, int numHamTop) {
if (!setPizzaSize(size)) {
System.out.println(size + " is invalid size." + "Use small, medium or large.");
}
setNumCheese(numCheeseTop);
setNumPep(numPepTop);
setNumHam(numHamTop);
}
public Pizza(String size, int numPepTop, int numHamTop) {
if (!setPizzaSize(size)) {
System.out.println(size + " is invalid size." + "Use small, medium or large.");
}
pizza_cheese = 0;
setNumPep(numPepTop);
setNumHam(numHamTop);
}
public Pizza(String size, int numHamTop) {
if (!setPizzaSize(size)) {
System.out.println(size + " is invalid size." + "Use small, medium or large.");
}
pizza_pep = 0;
setNumHam(numHamTop);
pizza_cheese = 0;
}
public Pizza(String size) {
if (!setPizzaSize(size)) {
System.out.println(size + " is invalid size." + "Use small, medium or large.");
}
pizza_cheese = 0;
pizza_pep = 0;
pizza_ham = 0;
}
public Pizza() {
pizza_size = "small";
pizza_cheese = 0;
pizza_pep = 0;
pizza_ham = 0;
}
public Pizza(Pizza copyPizza) {
pizza_size = copyPizza.getPizzaSize();
pizza_cheese = copyPizza.getNumCheese();
pizza_pep = copyPizza.getNumPep();
pizza_ham = copyPizza.getNumHam();
}
//Setters
public boolean setPizzaSize(String size) {
if (size.equalsIgnoreCase("small") || (size.equalsIgnoreCase("medium") || (size.equalsIgnoreCase("large")))) {
pizza_size = size.toLowerCase();
return true;
}
return false;
}
public void setNumCheese(int numCheeseTop) {
pizza_cheese = numCheeseTop;
}
public void setNumPep(int numPepTop) {
pizza_pep = numPepTop;
}
public void setNumHam(int numHamTop) {
pizza_ham = numHamTop;
}
//End of setters
//Getters
public String getPizzaSize() {
return pizza_size;
}
public int getNumCheese() {
return pizza_cheese;
}
public int getNumPep() {
return pizza_pep;
}
public int getNumHam() {
return pizza_ham;
}
//End of getters
public double calcCost() {
if (pizza_size.toLowerCase() == "small") {
return 10 + ((pizza_cheese + pizza_pep + pizza_ham) * 2);
}
if (pizza_size.toLowerCase() == "medium") {
return 12 + ((pizza_cheese + pizza_pep + pizza_ham) * 2);
}
if (pizza_size.toLowerCase() == "large") {
return 14 + ((pizza_cheese + pizza_pep + pizza_ham) * 2);
}
if (pizza_size.toLowerCase() != "small" && pizza_size.toLowerCase() != "medium"
&& pizza_size.toLowerCase() != "large") {
System.out.println("Invalid pizza size");
return 0;
}
return 0;
}
public String getDescription() {
return pizza_size + " pizza with " + pizza_cheese + " cheese toppings " + pizza_pep + " pepperoni toppings and "
+ pizza_ham + " ham toppings "; //+ " which is " + money.format(pizza2.calcCost());
}
//private String pizza_size;
//private int pizza_cheese, pizza_pep, pizza_ham;
public String pizza_size;
public int pizza_cheese, pizza_pep, pizza_ham;
} //End of Pizza class
PizzaOrderArray.java
import static java.lang.System.out;
public class PizzaOrderArray {
public String pizza_size;
public int pizza_cheese, pizza_pep, pizza_ham;
//private String pizza_size;
//private int pizza_cheese; pizza_pep; pizza_ham;
private Pizza[] pizza;
private int index = 0;
public PizzaOrderArray() {
System.out.println("PizzaOrderArray()");
index = 1;
pizza = new Pizza[index];
}
public PizzaOrderArray(int i) {
System.out.println("PizzaOrderArray(int i)");
index = 1;
pizza = new Pizza[index];
}
public PizzaOrderArray(PizzaOrderArray poa) {
System.out.println("PizzaOrderArray(PizzaOrderArray poa)");
pizza = new Pizza[poa.index];
index = poa.index;
for (int i = 0; i < poa.index; i++) {
System.out.println("PizzaOrderArray(PizzaOrderArray poa) for loop");
pizza[i] = new Pizza(poa.pizza[i]);
}
}
public void setPizza(int index1, Pizza newpizza) {
System.out.println("Inside of setPizza");
pizza[index1] = new Pizza(newpizza);
}
public String getPizzaSize() {
System.out.println("Inside of getPizzaSize");
return pizza_size;
}
public int getNumCheese() {
System.out.println("Inside of getNumCheese");
return pizza_cheese;
}
public int getNumPep() {
System.out.println("Inside of getNumPep");
return pizza_pep;
}
public int getNumHam() {
System.out.println("Inside of getNumHam");
return pizza_ham;
}
public String toString() {
String s = "";
int indexUsed = 0;
System.out.println("Inside of toString");
for (int i = 0; i < indexUsed; i++) {
s = (s + pizza[i].toString());
}
System.out.println("Inside of toString for loop");
return s;
}
public double calcTotal() {
double r = 0.0;
System.out.println("Inside of calcTotal");
for (int i = 0; i < index; i++) {
System.out.println("Inside of calcTotal for loop");
r = r + pizza[i].calcCost();
}
return r;
}
public boolean equals(PizzaOrderArray orderarray) {
boolean r = false;
System.out.println("Inside of equals");
if (orderarray.pizza.length != pizza.length) {
System.out.println("Inside of equals if");
return r;
}
for (int i = 0; i < orderarray.pizza.length; i++) {
if (pizza[i].equals(orderarray.pizza[i])) {
System.out.println("Inside of equals for-if");
r = true;
} else {
System.out.println("Inside of equals for-else");
return false;
}
}
System.out.println("Return of equals");
return r;
}
} //End of PizzaOrderArray class
V4_Project_15_page_418.java
import java.text.DecimalFormat;
import java.util.Scanner;
import java.util.Arrays;
public class V4_Project_15_page_418 {
public static void main(String args[]) {
//Order1
PizzaOrderArray order1 = new PizzaOrderArray();
Pizza pizzaone = new Pizza("Medium", 0, 0, 0);
Pizza pizzatwo = new Pizza("Small", 1, 0, 0);
order1.setPizza(0, pizzaone);
System.out.println("Order 1: ");
System.out.println(order1.toString());
System.out.println(order1);
System.out.println();
//Order2
Pizza pizzathree = new Pizza(pizzatwo);
PizzaOrderArray order2 = new PizzaOrderArray(2);
order2.setPizza(0, pizzaone);
order2.setPizza(0, pizzatwo);
System.out.println("Order 2: ");
System.out.println(order2.toString());
System.out.println(order2);
System.out.println();
//Order3
PizzaOrderArray order3 = new PizzaOrderArray(1);
order3.setPizza(0, pizzaone);
order3.setPizza(0, pizzatwo);
System.out.println("Order 3: ");
System.out.println(order3.toString());
System.out.println(order3);
System.out.println();
//Order4
PizzaOrderArray order4 = new PizzaOrderArray(order3);
System.out.println("Order 4: ");
System.out.println(order4.toString());
System.out.println(order4);
//TEST THE PROGRAM
System.out.println("TEST: The total for order 4 is: " + order4.calcTotal());
System.out.println();
//Order5
PizzaOrderArray order5 = new PizzaOrderArray(order1);
System.out.println("Order5: ");
System.out.println(order5);
System.out.println();
}//End of main class
}//End of V4_Project_15_page_418 class
Output:
PizzaOrderArray()
Inside of setPizza
Order 1:
Inside of toString
Inside of toString for loop
Inside of toString
Inside of toString for loop
PizzaOrderArray(int i)
Inside of setPizza
Inside of setPizza
Order 2:
Inside of toString
Inside of toString for loop
Inside of toString
Inside of toString for loop
PizzaOrderArray(int i)
Inside of setPizza
Inside of setPizza
Order 3:
Inside of toString
Inside of toString for loop
Inside of toString
Inside of toString for loop
PizzaOrderArray(PizzaOrderArray poa)
PizzaOrderArray(PizzaOrderArray poa) for loop
Order 4:
Inside of toString
Inside of toString for loop
Inside of toString
Inside of toString for loop
Inside of calcTotal
Inside of calcTotal for loop
Invalid pizza size
TEST: The total for order 4 is: 0.0
PizzaOrderArray(PizzaOrderArray poa)
PizzaOrderArray(PizzaOrderArray poa) for loop
Order5:
Inside of toString
Inside of toString for loop
Take a close look at the condition in this for loop, it isn't going to ever print anything since the condition is never true since i is never less than indexUsed which is 0.
public String toString() {
String s = "";
int indexUsed = 0;
System.out.println("Inside of toString");
for(int i = 0; i < indexUsed; i++)
s= (s + pizza[i].toString());
System.out.println("Inside of toString for loop");
return s;
}
Something also need pay attention to:
for(int i = 0; i < indexUsed; i++)
s= (s + pizza[i].toString());
System.out.println("Inside of toString for loop");
means:
for(int i = 0; i < indexUsed; i++) {
s= (s + pizza[i].toString());
}
System.out.println("Inside of toString for loop");
So this is System.out.println just misleading you, you are never "inside of" the for loop.
I think it's better to always use the braces '{}' with for/while loop.
The snippet
int indexUsed = 0;
System.out.println("Inside of toString");
for(int i = 0; i < indexUsed; i++)
s= (s + pizza[i].toString()); is wrong, your for loop is never executed since indexUsed is 0
In your toString method, the for loop condition never becomes true (before the first iteration itself, 0<0 becomes false & loop terminates without executing once) so the loop never executes.
You can try changing the for loop statement to:
for(int i = 0; i < index; i++)
Can someone see why the user can enter more than 27 apple, blueberry, or peanut pies? Even after declaring a final int for the max number of each type of pie.
The object here is to continually prompt the user for type of pie until the user wants to quit. Each time one of the valid inputs is entered it is stored in it's own array. After the user has indicated they are finished, calculations are done and a message is printed.
import javax.swing.JOptionPane;
public class CalcPieProfit {
public static void main(String[] args) {
final int MAX_PER_TYPE = 27;
int appleTotal = 0;
int blueberryTotal = 0;
int peanutTotal = 0;
String typeOfPie = getPieType();
while (!typeOfPie.equalsIgnoreCase("q")) {
if (typeOfPie.equalsIgnoreCase("apple")) {
String[] appleArray = fillApple(typeOfPie, MAX_PER_TYPE);
appleTotal++;
}
else if (typeOfPie.equalsIgnoreCase("blueberry")) {
String[] blueberryArray = fillBlueberry(typeOfPie, MAX_PER_TYPE);
blueberryTotal++;
}
else if (typeOfPie.equalsIgnoreCase("peanut")) {
String[] peanutArray = fillPeanut(typeOfPie, MAX_PER_TYPE);
peanutTotal++;
}
typeOfPie = getPieType();
}
if (typeOfPie.equalsIgnoreCase("q")) {
int totalPies = calcTotalPies(appleTotal, blueberryTotal, peanutTotal);
double profit = calcProfit(appleTotal, blueberryTotal, peanutTotal);
printReport(totalPies, appleTotal, blueberryTotal, peanutTotal, profit);
}
}
public static String getPieType() {
String pieType;
do {
try {
pieType = JOptionPane.showInputDialog("Enter a pie type:");
}
catch (NumberFormatException e) {
pieType = "";
}
if (!pieType.equalsIgnoreCase("apple") && !pieType.equalsIgnoreCase("blueberry") &&
!pieType.equalsIgnoreCase("peanut") && !pieType.equalsIgnoreCase("q")) {
JOptionPane.showMessageDialog(null, "Enter 'apple', 'blueberry', 'peanut', or 'q' only.");
}
} while (!pieType.equalsIgnoreCase("apple") && !pieType.equalsIgnoreCase("blueberry") &&
!pieType.equalsIgnoreCase("peanut") && !pieType.equalsIgnoreCase("q"));
return pieType;
}
public static String[] fillApple(String typeOfPie, int MAX_PER_TYPE) {
String[] appleArray = new String[MAX_PER_TYPE];
for (int i = 0; i < appleArray.length; i++) {
appleArray[i] = typeOfPie;
}
return appleArray;
}
public static String[] fillBlueberry(String typeOfPie, int MAX_PER_TYPE) {
String[] blueberryArray = new String[MAX_PER_TYPE];
for (int i = 0; i < blueberryArray.length; i++) {
blueberryArray[i] = typeOfPie;
}
return blueberryArray;
}
public static String[] fillPeanut(String typeOfPie, int MAX_PER_TYPE) {
String[] peanutArray = new String[MAX_PER_TYPE];
for (int i = 0; i < peanutArray.length; i++) {
peanutArray[i] = typeOfPie;
}
return peanutArray;
}
public static int calcTotalPies(int appleTotal, int blueberryTotal, int peanutTotal) {
int total = appleTotal + blueberryTotal + peanutTotal;
return total;
}
public static double calcProfit (int appleTotal, int blueberryTotal, int peanutTotal) {
final double APPLE_PROFIT = 5.94;
final double BLUEBERRY_PROFIT = 5.89;
final double PEANUT_PROFIT = 6.95;
double profit = (APPLE_PROFIT * appleTotal) + (BLUEBERRY_PROFIT * blueberryTotal) +
(PEANUT_PROFIT * peanutTotal);
return profit;
}
public static void printReport(int totalPies, int appleTotal, int blueberryTotal, int peanutTotal, double profit) {
if (totalPies > 0) {
JOptionPane.showMessageDialog(null,
"Pie Report\n\n" +
"Total pies: " + totalPies +
"\nTotal of apple pie: " + appleTotal +
"\nTotal of blueberry pie: " + blueberryTotal +
"\nTotal of peanut butter pie: " + peanutTotal +
"\nTotal profit: $" + String.format("%.2f", profit));
}
else {
JOptionPane.showMessageDialog(null, "Enjoy your day off.");
}
}
}
You are not really using the String[]s appleArray, blueberryArray and peanutArray - they are created in their respective method but not used anywhere else. For calculating the profits, you are (rightfully) only the total variables.
Instead of
if (typeOfPie.equalsIgnoreCase("apple")) {
String[] appleArray = fillApple(typeOfPie, MAX_PER_TYPE);
appleTotal++;
}
you should do something like
if (typeOfPie.equalsIgnoreCase("apple")) {
if (appleTotal >= MAX_PER_TYPE) {
JOptionPane.showMessageDialog(null, "Too many apples.");
} else {
appleTotal++;
}
}
(and the same for other pie types).
You're redeclaring the pie arrays each time you go to add them.
public static String[] fillApple(String typeOfPie, int MAX_PER_TYPE) {
String[] appleArray = new String[MAX_PER_TYPE];
for (int i = 0; i < appleArray.length; i++) {
appleArray[i] = typeOfPie;
}
return appleArray;
}
Each time you call this method, a new "appleArray" is generated. If you want it to persist between calls to this method, declare the appleArray as private static outside of the loop, and reference that instead.
So I have been trying to run my LibraryTest.java program but it crashes when it has to use sortBooksByTitle() and sortBooksByNumPages(). The two sorting methods compile, but when I try to run the test class, it crashes.
These are my three java files.
Book.java
public class Book {
private String author;
private String title;
private int numPages;
public Book() {
title = "EMPTY";
}
public Book(String titleIn, String authorIn, int numPagesIn) {
title = titleIn;
author = authorIn;
numPages = numPagesIn;
}
public String getAuthor() {
return author;
}
public String getTitle() {
return title;
}
public int getNumPages() {
return numPages;
}
public String toString() {
return title + " by " + author + " (" + numPages + " pages)";
}
}
Library.java
import java.util.Random;
import java.util.Arrays;
public class Library {
private Book[] array;
private int count;
private Random randomBook = new Random();
public Library(int numBooks) {
array = new Book[numBooks];
count = 0;
}
public int getCount() {
return count;
}
public void addBook(Book b) {
//check if program can add new book
if (count < array.length) {
array[count] = b;
count++;
} //if array is full, a message is thrown
else {
System.out.println("The Library is full!");
}
}
//Adds content of a library to another library.
public void addLibrary(Library l) {
for (Book b : l.array) {
addBook(b);
}
}
//Returns a book after receiving a String input.
public Book getBook(String book) {
for (int i = 0; i < array.length - 1; i++) {
String titleBook = array[i].getTitle();
if (titleBook.equals(book)) {
return array[i];
}
}
Book newBook = new Book();
return newBook;
}
//Returns the book located in the array index given by the input.
public Book getBook(int index) {
if (index < array.length) {
System.out.printf("num: %d", index);
return array[index - 1];
}
Book newBook = new Book();
return newBook;
}
//Uses the random number generator and returns a book located in the array which
//index is the random number obtained.
public Book getBook() {
int num = randomBook.nextInt(array.length);
//System.out.printf("random num: %d", num);
return array[num];
}
//Sorts books alphabetically.
public void sortBooksByNumPages() {
for (int i = 0; i < array.length - 1; i++) {
for (int j = i + 1; j < array.length; j++) {
if (array[i].getNumPages() > array[j].getNumPages()) {
Book temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
}
//Sorts books by number of pages in ascending order.
public void sortBooksByTitle() {
for (int i = 0; i < array.length - 1; i++) {
for (int n = i; n < array.length; n++) {
if (array[n].getTitle().compareToIgnoreCase(array[i].getTitle()) < 0) {
Book temp = array[i];
array[i] = array[n];
array[n] = temp;
}
}
}
}
//Output each book's information.
public String toString() {
String s = "Number of books: " + count + "\n";
for (int i = 0; i < array.length; i++) {
s = s + array[i] + "\n";
}
return s;
}
}
LibraryTest.java
public class LibraryTest {
public static void main(String args[]) {
Library lib = new Library(3);
Book b1 = new Book("Java: How to Program", "Deitel and Deitel", 1496);
lib.addBook(b1);
Book b2 = new Book("A Brief History of Time", "Stephen Hawking", 212);
lib.addBook(b2);
Book b3 = new Book("The Art of War", "Sun Tzu", 384);
lib.addBook(b3);
Book b4 = new Book("Ender's Game", "Orson Scott Card", 352);
// This addBook call should fail since the Library lib is full
lib.addBook(b4);
Book b5 = new Book("The Singularity is Near", "Ray Kurzweil", 672);
Library lib2 = new Library(10);
lib2.addBook(b4);
lib2.addBook(b5);
System.out.print("\n\nOriginal library contents\n");
// This should display that there are 3 books in the library & info
System.out.print(lib);
System.out.print("\n\nAfter combining libraries\n");
lib2.addLibrary(lib);
lib = lib2;
// This should display that there are 5 books in the library & info
System.out.print(lib);
System.out.print("\n\nSorted by title\n");
try {
lib.sortBooksByTitle();
} catch (Exception e) {
System.out.println(e.toString());
System.out.println(e.getMessage());
}
// This should display the books in alphabetical order by title
System.out.print(lib);
/*
* System.out.print("\n\nSorted by number of pages\n");
* lib.sortBooksByNumPages(); // This should display the books in
* increasing order of the number of //pages each one has
* System.out.print(lib);
*/
// This should display Ender's Game
System.out.print("\n\nBook 2:\n" + lib.getBook(1));
// This should display the EMPTY book
System.out.print("\n\nBook 20:\n" + lib.getBook(20));
System.out.print("\n\nBook 'The Art of War':\n"
+ lib.getBook("The Art of War"));
// This should randomly display a book from the library (potentially
//different each time)
System.out.print("\n\nRandom book:\n" + lib.getBook());
}
}
Again the 3 files compile just fine but crash when I try to run. Help me please. Thank you.
The problem is a NullPointerException thrown in your sortBooksByTitle() method. The specific line where the exception is thrown is
if (array[n].getTitle().compareToIgnoreCase(array[i].getTitle()) < 0).
This is happening because when you create lib2you do so by calling new Library(10) which causes it to initialize its array to size 10. At the time of calling sortBooksByTitle() the array contains 5 books and 5 null values. Once the loop has gone through the 5 books it hits a null and calls getTitle() on it, which results in your NPE.