Java values of toString() not printing - java

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++)

Related

Invalid array display

Good day, I have the following assignment:
https://prnt.sc/113pc7j
My problem is the first assignment of the fourth item. I prescribed filling the array with random objects, however, when I want to display this array on the screen, I get different results all the time.
My code:
The interface itself:
interface VehicleAndWorkers
{
String cars();
}
First class that implements the interface:
public class TaxiStation implements VehicleAndWorkers{
TrucksLogistic trucks = new TrucksLogistic();
public String[] cars = {"KIA", "Hyundai", "Volkswagen", "Lada", "Datsun", "Skoda"};
int quantCars = 150;
int workers = 300;
public String cars() {
System.out.println("List of models of our taxi fleet: ");
for (int i = 0; i < cars.length; i++) {
System.out.println(cars[i]);
}
return null;
}
#Override
public boolean equals(Object obj)
{
return trucks.quantTrucks == this.quantCars;
}
#Override
public int hashCode() {
return Objects.hash(trucks, quantCars);
}
#Override
public String toString() {
return cars();
}
}
Second class that implements the interface:
public class TrucksLogistic implements VehicleAndWorkers {
String[] trucks = {"Kenworth W900", "Volvo FH16", "Scania R730", "MAN TGS 18.400", "МАЗ 6430",
"КАМАЗ-5490 НЕО 2"};
int quantTrucks = 40;
int workers = 100;
public String cars()
{
System.out.println("Our company model list: ");
for (int i = 0; i < trucks.length; i++)
{
System.out.println(trucks[i]);
}
System.out.println("Amount of workers: " + workers);
System.out.println("Number of trucks: " + quantTrucks);
System.out.println("The ratio of the number of truck models to the number of trucks: " +
Math.round(trucks.length / quantTrucks));
return null;
}
#Override
public String toString() {
return cars();
}
}
The class in which I tried to implement working with ArrayList (filling, displaying, etc.):
public class InterfaceArray {
ArrayList<VehicleAndWorkers> array = new ArrayList<>();
public void setArray() {
int randomLength = (int) Math.floor(random() * 10);
for (int i = 0; i < randomLength; i++) {
Random random = new Random();
int minRandomNum = 1;
int maxRandomNum = 2;
int diffRandomNum = maxRandomNum - minRandomNum;
int randomNum = random.nextInt(diffRandomNum + 1) + minRandomNum;
if (randomNum == 1) {
array.add(new TrucksLogistic() {
#Override
public String cars() {
int num = (int) Math.floor(random() * trucks.length);
quantTrucks = (int) Math.floor(random() * 100);
Random random = new Random();
int minWorkers = quantTrucks;
int maxWorkers = 200;
int diffWorkers = maxWorkers - minWorkers;
workers = random.nextInt(diffWorkers + 1);
workers += minWorkers;
System.out.println("Number of trucks: " + quantTrucks);
System.out.println("Amount of workers: " + workers);
System.out.println("Average number of workers per truck: " + Math.round(workers /
quantTrucks));
return "Priority truck brand/model: " + trucks[num];
}
});
} else {
array.add(new TaxiStation() {
#Override
public String cars() {
int num = (int) Math.floor(random() * cars.length);
quantCars = (int) Math.floor(random() * 100);
Random random = new Random();
int minWorkers = quantCars;
int maxWorkers = 200;
int diffWorkers = maxWorkers - minWorkers;
workers = random.nextInt(diffWorkers + 1);
workers += minWorkers;
System.out.println("Number of passenger cars: " + quantCars);
System.out.println("Amount of workers: " + workers);
System.out.println("Average number of employees per vehicle: " + Math.round(workers / quantCars));
return "Priority car brand/model:" + cars[num];
}
});
}
}
}
public void getArray() {
for (VehicleAndWorkers element : array) {
System.out.println("");
System.out.println(element);
System.out.println("");
}
}
public void sameElements() {
//// Set<VehicleAndWorkers> arrayTwo = new LinkedHashSet<>(array);
//// for (VehicleAndWorkers element : arrayTwo)
//// System.out.println(element + "\n");
//
// for (int element = 0; element < array.size() - 1; element++)
// {
// for (int i = element + 1; i < array.size(); element++)
// {
// if (array.get(element).equals(element + 1))
// {
// arrayTwo.add(array.get(element + 1));
// }
// }
// array.remove(array.get(element));
// }
// for (VehicleAndWorkers element : arrayTwo)
// System.out.println(element.toString());
}
public void sameTypeElements() {
ArrayList<VehicleAndWorkers> arrayTwo = new ArrayList<>();
// for (VehicleAndWorkers element : array)
// {
// if (element)
// }
}
}
Well, the class in which the methods from the previous class are applied:
public class ConsoleInterface {
void doChoice()
{
InterfaceArray interfaceArray = new InterfaceArray();
printOptions();
Scanner scan = new Scanner(System.in);
int choice = scan.nextInt();
while (choice >= 0 && choice < 5) {
if (choice == 0) {
interfaceArray.setArray();
interfaceArray.getArray();
printOptions();
choice = scan.nextInt();
}
else if (choice == 1) {
interfaceArray.setArray();
printOptions();
choice = scan.nextInt();
}
else if (choice == 2) {
interfaceArray.sameElements();
printOptions();
choice = scan.nextInt();
}
else if (choice == 3) {
interfaceArray.sameTypeElements();
printOptions();
choice = scan.nextInt();
}
else if (choice == 4) {
interfaceArray.getArray();
printOptions();
choice = scan.nextInt();
}
}
}
void printOptions()
{
System.out.println("Choose an action: \n");
System.out.println("0 - Fill the array with random elements and display it on the screen. \n");
System.out.println("1 - Fill the array with random elements. \n");
System.out.println("2 - Find objects in the array,\n" +
" whose functional method returns the same result. \n");
System.out.println("3 - Split the original array into two arrays, \n" +
" which will store the same type of elements. \n");
System.out.println("4 - Display the array(-s) to the screen.\n");
System.out.println("Any key - Exit the application.\n");
}
}
An example of how the program works:
I fill the array and immediately output it to the console: https://prnt.sc/113qmkr
I get the result:
https://prnt.sc/113qurt
https://prnt.sc/113qvaq
I try again to display all the objects in the array: https://prnt.sc/113qvz4
And... I get completely different results:
https://prnt.sc/113qwhx
https://prnt.sc/113qwps
Moreover, as you may have noticed, the length of the array is preserved, but the objects themselves are already different.
Honestly, I don't know what the problem might be, the teacher at the university also threw up his hands, so I will be glad to any criticism, comments and suggestions. Thank you in advance.

For loop not initiated in method

I'm very new to coding, so I was practicing with some simple stuff, and encountered a problem I've been trying to solve for about 2 hours now, and I have no idea what's even wrong with it.
The problem is that when I invoke either crate.fillCrate(); or crate.emptyCrate();, nothing appears in the console, and when I invoke crate.crateInfo(); the following appears in the console:
A nice crate of Heineken
It contains 24 slots
slots: are filled.
slots: are empty.
I guess this means my for-loops don't start, but I have no idea why...
My Main class:
public class Main {
public static void main(String[] args) {
Crate crate = new Crate(24, "Heineken");
}
}
My Crate Class:
public class Crate {
private int crateSize;
private Bottle[] bottles = new Bottle[crateSize];
public String brand = null;
public Crate(int crateSize, String brand) {
this.crateSize = crateSize;
this.brand = brand;
}
public void fillCrate(){
for(int i = 0; i < bottles.length; i++) {
if(bottles[i] == null && !bottles[i].getSpotInfo()) {
bottles[i] = new Bottle(true);
System.out.println("Spot " + (i+1) + " is filled.");
} else {
System.out.println("Spot " + (i+1) + " was already full");
}
}
}
public void emptyCrate() {
for(int i = 0; i < bottles.length; i++) {
if(bottles[i] != null && bottles[i].getSpotInfo()) {
bottles[i].makeSpotEmpty();
System.out.println("Spot " + (i+1) + " is empty.");
} else {
System.out.println("Spot " + (i+1) + " was already empty");
}
}
}
public void crateInfo() {
System.out.println("A nice crate of " + brand);
System.out.println("It contains " + crateSize + " slots");
System.out.print("slots: ");
for(int i = 0; i < bottles.length; i++) {
if(bottles[i] != null && bottles[i].getSpotInfo()) {
System.out.print((i+1));
}
}
System.out.println(" are filled.");
System.out.print("slots: ");
for(int c = 0; c < bottles.length; c++) {
if(bottles[c] != null && !bottles[c].getSpotInfo()) {
System.out.print((c+1));
}
}
System.out.println(" are empty.");
}
}
And my Bottle class:
public class Bottle {
private boolean occupiesSpot = false;
public Bottle(boolean occupiesSpot) {
this.occupiesSpot = occupiesSpot;
}
public void makeSpotEmpty() {
occupiesSpot = false;
}
public boolean getSpotInfo() {
return occupiesSpot;
}
}
private int crateSize;
private Bottle[] bottles = new Bottle[crateSize];
the bottles gets the size of 0 as crateSize is not initialized yet, you should instead do
public Crate(int crateSize, String brand) {
this.crateSize = crateSize;
this.brand = brand;
this.bottles = new Bottle[crateSize];
}
and also
if (bottles[i] == null && bottles[i].getSpotInfo())
this line will cause a NullPointerException if the bottle is null, because you cannot call a method (getSpotInfo) on a null object. Thanks for #Turing85 for pointing this out as well.

user input still stored after exceeding array length

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.

Fix NullPointerException? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
How could I get the program to output all the information? IT currently returns a NullPointException error. Thanks.
I am supposed to use the delete methods just as they are, I cannot change them, but I am sure there must be something I can do.
public class TestCandidate7
{
public static int getTotal(Candidate[] election)
{
int total = 0;
for(Candidate candidate : election )
{
total += candidate.numVotes;
}
return total;
}
public static void printResults(Candidate[] election)
{
double percent;
System.out.println("Candidate Votes Received % of Total Votes");
for (int x = 0; x < election.length; x++)
{
percent = (double) (election[x].votes()) / getTotal(election) * 100;
System.out.printf("%-15s %10d %20.0f", election[x].getName(), election[x].votes(), percent);
System.out.println();
}
}
public static void deleteByLoc(Candidate[] election,
int location)
{
if ((location > 0) && (location < election.length))
{
//move items up in the array -
for(int index = location; index < election.length -1; index++)
election[index] = election[index + 1];
election[election.length-1] = null;
}
}
public static void deleteByName(Candidate[] election,
String find)
{
int location = 0;
int index;
// find location of item you want to delete
for(index = 0; index < election.length; index++)
if ((election[index] != null) && (election[index].getName().equals(find)))
{
location = index;
break;
}
else if (election[index] == null)
{
location = -1;
break;
}
if ((index != election.length) && (location >= 0))
{ //move items up in the array
for(index = location; index < election.length -1; index++)
election[index] = election[index + 1];
election[election.length-1] = null;
}
}
public static void main(String[] args)
{
Candidate[] election = new Candidate[10];
// create election
election[0] = new Candidate("John Smith", 5000);
election[1] = new Candidate("Mary Miller", 4000);
election[2] = new Candidate("Michael Duffy", 6000);
election[3] = new Candidate("Tim Robinson", 2500);
election[4] = new Candidate("Joe Ashtony", 1800);
election[5] = new Candidate("Mickey Jones", 3000);
election[6] = new Candidate("Rebecca Morgan", 2000);
election[7] = new Candidate("Kathleen Turner", 8000);
election[8] = new Candidate("Tory Parker", 500);
election[9] = new Candidate("Ashton Davis", 10000);
System.out.println("Original results:");
System.out.println();
printResults(election);
System.out.println();
System.out.println("Total of votes in election: " + getTotal(election) );
System.out.println();
deleteByLoc(election, 6);
System.out.println("Deleted location 6:");
System.out.println();
printResults(election);
System.out.println();
System.out.println("Total of votes in election: " + getTotal(election) );
System.out.println();
deleteByName(election, "Kathleen Turner");
System.out.println("Deleted Kathleen Turner:");
System.out.println();
printResults(election);
System.out.println();
System.out.println("Total of votes in election: " + getTotal(election) );
System.out.println();
}
}
Candidate
public class Candidate
{
// instance variables
int numVotes;
String name;
/**
* Constructor for objects of class InventoryItem
*/
public Candidate(String n, int v)
{
// initialise instance variables
name = n;
numVotes = v;
}
public int votes()
{
return numVotes;
}
public void setVotes(int num)
{
numVotes = num;
}
public String getName()
{
return name;
}
public void setName(String n)
{
name = n;
}
public String toString()
{
return name + " received " + numVotes + " votes.";
}
}
When you "delete" array elements, after the shift you assign null to the most right element of the array.
In your getTotal() you traverse the entire array and retrieve the value of numVotes for each element. When you reach the null element you are getting the exception since null does not have any fields..

java.lang.ArrayIndexOutOfBoundsException: 10 Array

I need some help with this one. I have trying to get this array to work properly but do not know what I am doing wrong. I am a noob to java and really need some help
private static int respondentID;
private static int count;
static void enterQuestions() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
private String surveyName;
private boolean surveyStart = true;
private boolean surveyStop = true;
private String question [] = new String[10];
private int responses[][]= new int[10][10];
Scanner input = new Scanner(System.in);
// first overloaded constructor
public Phase2() {
this( "Customer Survey" );
respondentID = 0;
count = 0;
} // end
// second overloaded constructor
public Phase2( String title ) {
surveyName = title;
respondentID = 0;
count = 0;
} // end constructor Survey
// method to be called when a user starts filling out a survey ( surveyStart will have been set to "true" )
public int startSurveyCount( int ct ) { // parameter for testing only
if( surveyStart ) {
if( respondentID > 0 ) {
if( count >= respondentID ) {
count++;
} else {
setCount( getRespondentID() );
}
} else {
//test
setCount( ct );
count = getCount();
count++;
setCount( count - 1 );
}
}
return count;
} // end method
// method to be called when a survey is successfully
public int generateRespondentID() {
if( surveyStop ) {
//
count = getCount();
setRespondentID( count );
} else {
if( count < 2 ) {
count = 0;
respondentID = 0;
} else {
count--;
setCount( count );
}
}
return respondentID;
} // end method generateRespondentID
public void setRespondentID( int count ) {
// count is the number of completed surveys.
respondentID = count;
respondentID++; // and then incremented by 1.
} //end method
public int getRespondentID() {
return respondentID;
} // end method
public void setSurveyTitle( String title ) {
surveyName = title;
} // end method
public String getSurveyTitle() {
return surveyName;
} // end method
public void setCount( int ct ) {
count = ct;
} // end method
public int getCount() {
return count;
} // end method
public void setSurveyStart( boolean surveySt ) {
surveyStart = surveySt;
} // end method
public boolean getSurveyStart() {
return surveyStart;
} // end method
public void setSurveySubmit( boolean surveySub ) {
surveyStop = surveySub;
} // end method
public boolean getSurveySubmit() {
return surveyStop;
} // end method
public void logResponse(int respondentID, int questionNumber, int responseEntered)
{
responses[respondentID] [questionNumber-1] = responseEntered;
}
public void displaySurveyResults (int no)
{
for (int j=0; j<10; j++)
System.out.print("Question"+(no)+" : " + question[no-1]+"Reply");
if (responses[respondentID][no] == 0)
{
System.out.print("NO");
}
else
{
System.out.print("Yes");
}
}
public void enterQuestion()
{
for (int i=0; i<10; i++)
{
System.out.println("Enter Question "+(i+1)+" : ");
question[i] = input.nextLine();
}
}
public void displayQuestionStats(int no)
{
int answer;
System.out.print("Question"+(no)+" : "+question[no-1]+" (0-No/1-Yes) : ");
answer = input.nextInt();
logResponse(respondentID, no, answer);
}
}
This is my tester
public static void main(String[] args) {
Scanner input = new Scanner( System.in );
System.out.println( "Below are the results of running the no–argument");
// demonstrates the no–arg constructor
Phase2 noArgSurvey = new Phase2();
System.out.printf( "The no–argument survey values are:\ntitle: %s\n"
+ "initial value of respondentID: %d\ncount: %d\n",
noArgSurvey.getSurveyTitle(), noArgSurvey.getRespondentID(),
noArgSurvey.getCount() );
// demonstrates the constructor with a title argument ( for user input of survey title )
System.out.println( "\nPlease enter a name for the survey" );
String inputTitle = input.nextLine();
System.out.println(); // inserts a blank line
Phase2 titleArgConst = new Phase2( inputTitle );
System.out.printf( "Survey Name is: %s\n"
+ "initial values of:\nrespondentID: %d\ncount: %d\n\n",
titleArgConst.getSurveyTitle(), titleArgConst.getRespondentID(),
titleArgConst.getCount() );
//respondent id test
System.out.println( "This will test the generateRespondentID method.\n\n"
+ "Enter the number of surveys that have been taken");
int testInt = input.nextInt();
// values for respondentID and count after 1 survey has been successfully submitted
System.out.println( "\nAssuming " + testInt + " surveys submitted");
Phase2 oneDone = new Phase2();
oneDone.startSurveyCount( testInt );
oneDone.generateRespondentID();
System.out.printf( "The Respondent ID is: %d\ncount: %d\n\n",
oneDone.getRespondentID(), oneDone.getCount() );
noArgSurvey.enterQuestion();
for(int i = 1; i <= 10; i++)
{
noArgSurvey.displayQuestionStats(i);
}
//Display The Inputs Entered by User
System.out.println("Result for Survey with Title \""+titleArgConst.getSurveyTitle()+"\" :");
for(int i=1; i<11; i++)
{
noArgSurvey.displaySurveyResults(i);
}
} // end main method
} // end class SurveyTest
Change loop condition to
for(int i = 1; i < 10; i++)
Java follows Zero indexing. So in your case question and responses array is of size 10 which means it will iterate from 0 to 9 use for(int i = 1; i < 10; i++) instead for iterating. or use arrayName.length length is a variable provided by JVM which gives you the size of array at runtime.
AS Vishrant mentioned *Java follows Zero indexing. So in your case question and responses array is of size 10 which means it will iterate from 0 to 9 *
in your tester class, you are trying to access 10th index in loop in 2 places
for(int i = 1; i <= 10; i++) (1)
{
noArgSurvey.displayQuestionStats(i);
}
for(int i=1; i<11; i++) (2)
{
noArgSurvey.displaySurveyResults(i);
}
You should to write
for(int i = 0; i < 10; i++) (1)
{
noArgSurvey.displayQuestionStats(i);
}
for(int i=0; i<10; i++) (2)
{
noArgSurvey.displaySurveyResults(i);
}
EDIT Addition
public void displaySurveyResults (int no)
{
for (int j=0; j<10; j++)
System.out.print("Question"+(no)+" : " + question[no]+"Reply"); <<<--------- change [no-1] to [no]
if (responses[respondentID][no] == 0)
{
System.out.print("NO");
}

Categories

Resources