For loop not initiated in method - java

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.

Related

How can I assign the driver to UNO DiscardPile.java?

I'm creating an UNO project and am a bit confused about how to assign the drivers to my DiscardPile class.
Thank you in advance for any answers you may give.
Sincerely,
Jayda M
I've asked my fellow students for assistance and have scoured the internet for anything that could be helpful with no luck. My professor isn't helpful at all haha
This is the full code for the Driver.java file. If you need me to give you any of the others I have no problem doing so.
package unoGame;
import java.util.Random;
//import java.util.Collections;
public class Driver {
public static unoDeck theDeck = new unoDeck();
public static PlayerHand[] thePlayers;
public static DiscardPile dp = new DiscardPile();
public static int nextPlayer;
public static Random getRandom = new Random();
public static void main(String[] args) {
// TODO Auto-generated method stub
thePlayers = new PlayerHand[3];
thePlayers[0] = new PlayerHand("name 1");
thePlayers[1] = new PlayerHand("name 2");
thePlayers[2] = new PlayerHand("name 3");
theDeck.shuffle();
System.out.println("Here is the Deck: " + theDeck);
System.out.println(" Welcome to UNO! ");
if (dp.isEmpty()) {
System.out.println(" Discard is Empty ");
}
else {
System.out.println(" Not Empty ");
}
for (int i = 0; i < 7; i++) {
for (int j = 0; j < thePlayers.length; j++) {
thePlayers[j].addCard(theDeck.deal());
}
}
nextPlayer = 0;
showPlayers();
dp.addCard(theDeck.deal());
while (checkForWin() == false) {
findNextPlayer();
if (theDeck.isEmpty()) {
theDeck.replenish(dp.clear());
}
playerTurn();
}
System.out.println(thePlayers[nextPlayer], getName() + " Wins!")
}
public static void showPlayers() {
for (PlayerHand p : thePlayers)
System.out.println(p);
}
public static boolean checkForWin() {
if (p.isWin()) {
win = true;
}
return win;
}
public static void findNextPlayer() {
nextPlayer++;
nextPlayer = nextPlayer % thePlayers.length;
if(dp.getTopCard().getValue()=="SK") {
nextPlayer++;
nextPlayer = nextPlayer % thePlayers.length;
}
if(dp.getTopCard().getValue() == "D2") {
for(int i = 0; i <= 1; i++) {
thePlayers[nextPlayer].addCard(theDeck.deal());
}
}
if(dp.getTopCard().getValue() == "W4") {
for(int i = 0; i <= 3; i++) {
thePlayers[nextPlayer].addCard(theDeck.deal());
}
}
if(dp.getTopCard().getValue() == "RV") {
for(int i = 0; i < thePlayers.length / 2; i++) {
PlayerHand rev = thePlayers[i];
thePlayers[i] = thePlayers[thePlayers.length - i -1];
rev = thePlayers[thePlayers.length - i -1];
if(nextPlayer == 0) {
nextPlayer = 0;
}
if(nextPlayer == 2) {
nextPlayer = 1;
}
}
nextPlayer++;
}
}
public static void playerTurn() {
if (thePlayers[nextPlayer].hasMatch(dp.getTopCard())) {
System.out.println(thePlayers[nextPlayer].getName() + " has a match!");
unoCard c = thePlayers[nextPlayer].playCard(dp.getTopCard());
dp.addCard(c);
if(c.getValue().equals("W")) {
c.setColor(theDeck.newColor());
}
if(c.getValue().equals("W4")) {
c.setColor(theDeck.newColor());
}
System.out.println(thePlayers[nextPlayer].getName() + " played a: " dp.getTopCard());
System.out.println(thePlayers[nextPlayer]);
}
else {
unoCard c = theDeck.deal();
thePlayers[nextPlayer]c.addCard(c);
System.out.println(thePlayers[nextPlayer].getName() + " drew a: " + c);
}
}
}
There are errors are on these lines of code: 46, 50, 57, 58, 60, 106 and 111. Most of them are saying they're undefined, and I'm unsure of where to do so amongst my files. I'm expecting the Driver to run the game as a whole, so because it's gone wack I can't run the build properly. If you need more information to work with, I'll gladly give it to you!
EDIT:
The lines and/or words where the errors are taking place have asterisks around them
The error descriptions with their corresponding lines
The printed console error after running Driver. Hopefully this works for the Reproducible Example required :)
Here is your Driver class with compilation problems fixed. I suggest you compare it with your current code in order to see what I changed.
I also needed to add method replenish() in class unoDeck because it didn't exist and is called from class Driver. Right now that method does nothing. As I said, I only added it in order to fix the compilation error.
package unoGame;
import java.util.Random;
public class Driver {
public static unoDeck theDeck = new unoDeck();
public static PlayerHand[] thePlayers;
public static DiscardPile dp = new DiscardPile();
public static int nextPlayer;
public static Random getRandom = new Random();
public static void main(String[] args) {
thePlayers = new PlayerHand[3];
thePlayers[0] = new PlayerHand("name 1");
thePlayers[1] = new PlayerHand("name 2");
thePlayers[2] = new PlayerHand("name 3");
theDeck.shuffle();
System.out.println("Here is the Deck: " + theDeck);
System.out.println(" Welcome to UNO! ");
if (dp.isEmpty()) {
System.out.println(" Discard is Empty ");
}
else {
System.out.println(" Not Empty ");
}
for (int i = 0; i < 7; i++) {
for (int j = 0; j < thePlayers.length; j++) {
thePlayers[j].addCard(theDeck.deal());
}
}
nextPlayer = 0;
showPlayers();
dp.addCard(theDeck.deal());
while (checkForWin() == false) {
findNextPlayer();
if (theDeck.isEmpty()) {
theDeck.replenish(dp.clear());
}
playerTurn();
}
System.out.println(thePlayers[nextPlayer].getName() + " Wins!");
}
public static void showPlayers() {
for (PlayerHand p : thePlayers)
System.out.println(p);
}
public static boolean checkForWin() {
boolean win = false;
if (thePlayers[nextPlayer].isWin()) {
win = true;
}
return win;
}
public static void findNextPlayer() {
nextPlayer++;
nextPlayer = nextPlayer % thePlayers.length;
if (dp.getTopCard().getValue() == "SK") {
nextPlayer++;
nextPlayer = nextPlayer % thePlayers.length;
}
if (dp.getTopCard().getValue() == "D2") {
for (int i = 0; i <= 1; i++) {
thePlayers[nextPlayer].addCard(theDeck.deal());
}
}
if (dp.getTopCard().getValue() == "W4") {
for (int i = 0; i <= 3; i++) {
thePlayers[nextPlayer].addCard(theDeck.deal());
}
}
if (dp.getTopCard().getValue() == "RV") {
for (int i = 0; i < thePlayers.length / 2; i++) {
PlayerHand rev = thePlayers[i];
thePlayers[i] = thePlayers[thePlayers.length - i - 1];
rev = thePlayers[thePlayers.length - i - 1];
if (nextPlayer == 0) {
nextPlayer = 0;
}
if (nextPlayer == 2) {
nextPlayer = 1;
}
}
nextPlayer++;
}
}
public static void playerTurn() {
if (thePlayers[nextPlayer].hasMatch(dp.getTopCard())) {
System.out.println(thePlayers[nextPlayer].getName() + " has a match!");
unoCard c = thePlayers[nextPlayer].playCard(dp.getTopCard());
dp.addCard(c);
if(c.getValue().equals("W")) {
c.setColor(theDeck.newColor());
}
if(c.getValue().equals("W4")) {
c.setColor(theDeck.newColor());
}
System.out.println(thePlayers[nextPlayer].getName() + " played a: " + dp.getTopCard());
System.out.println(thePlayers[nextPlayer]);
}
else {
unoCard c = theDeck.deal();
thePlayers[nextPlayer].addCard(c);
System.out.println(thePlayers[nextPlayer].getName() + " drew a: " + c);
}
}
}

java - Function in class

I need to write a function to College department :
Add function adds additional lecturer.
Action returns false if there is no place to add additional lecturer, and at the same true if the lecturer was successfully added.
What I had written so far:
public boolean newLecturer(Lecturer[] AllLecturer) {
int MaxLecturer = 0;
MaxLecturer = this.maxLecturer;
int sum = 0;
sum += 1;
if (sum < MaxLecturer) {
System.out.println("true");
return true;
}
else {
System.out.println("false");
return false;
}
}
The function does not work properly, It always returns true (because that the Max Lecturer always bigger than sum).
main:
public class main {
public static void main(String[]args){
Lecturer[] L1 = new Lecturer[]{new Lecturer("David",3,"Banana",1001)};
Lecturer[] L2 = new Lecturer[]{new Lecturer("Yossi",5,"apple",1002)};
Lecturer[] L3 = new Lecturer[]{new Lecturer("Y",2,"t",1003)};
College myCollege = new College("College1",20,L1,3);
//System.out.println(myCollege);
//myCollege.allLecturer=L2;
//System.out.println(myCollege);
myCollege.newLecturer(L1);
myCollege.newLecturer(L2);
myCollege.newLecturer(L3);
}
}
class College (Function here):
public class College {
public String name;
public int numOfLecturer;
public Lecturer[] allLecturer;
public int maxLecturer;
// constructor
public College(String Name, int NumOfLecturer, Lecturer[] AllLecturer,
int MaxLecturer) {
this.name = Name;
this.numOfLecturer = NumOfLecturer;
this.allLecturer = AllLecturer;
this.maxLecturer = MaxLecturer;
}
public College(String Name) {
this.name = Name;
}
public College(Lecturer[] AllLecturer) {
this.allLecturer = AllLecturer;
}
public boolean newLecturer(Lecturer[] AllLecturer) {
int MaxLecturer = 0;
MaxLecturer = this.maxLecturer;
int sum = 0;
sum += 1;
if (sum < MaxLecturer) {
System.out.println("true");
return true;
}
else {
System.out.println("false");
return false;
}
}
#Override
public String toString() {
String lecturers = "";
for (Lecturer lecturer : allLecturer) {
lecturers += lecturer;
}
return "[Name College: " + name + "] " + " [num Of Lecturer: "
+ numOfLecturer + "]" + " [all Lecturer: " + lecturers + "]"
+ " [max Lecturer " + maxLecturer + "]";
}
}
class Lecturer:
public class Lecturer {
public String name;
public int numOfTimesPenFalls;
public String favoriteIceCream;
public int autoNumber;
// constructor
public Lecturer(String Name, int NumOfTimesPenFalls,
String FavoriteIceCream, int AutoNumber) {
this.name = Name;
this.numOfTimesPenFalls = NumOfTimesPenFalls;
this.favoriteIceCream = FavoriteIceCream;
this.autoNumber = AutoNumber;
}
public Lecturer(String Name) {
this.name = Name;
}
#Override
public String toString() {
return "[name: " + name + "] " + " [num Of Times Pen Falls: "
+ numOfTimesPenFalls + "] " + " [favorite Ice Cream: "
+ favoriteIceCream + "] " + " [auto Number: " + autoNumber
+ "]";
}
}
And finally how can I print it?
Like this gives a compiler error:
myCollege.newLecturer("David",2,"Apple",1004);
thank you.
You're new; you need a lot of help.
Start by learning and following Java coding standards. Variable names should start with lower case. Classes start with upper. Deviations from that make your code hard to read.
Your method is wrong. You need something like this inside that class:
private static final int MAX_LECTURERS = 3;
private int numLecturers = 0;
private Lecturer [] lecturers = new Lecturer[MAX_LECTURERS];
public boolean addLecturer(Lecturer lecturer) {
boolean addedLecturer = false;
if (this.numLecturers < MAX_LECTURERS) {
this.lecturers[numLecturers++] = lecturer;
addedLecturer = true;
}
return addedLecturer;
}
Here's how you use this method:
Lecturer newLecturer = new Lecturer("foo", 1, "bar", 3);
college.addLecturer(newLecturer);
Please stop with all that array nonsense. The array is inside the College class.
The sum variable in your code is a local variable, its scope is only at the function level. This means the sum always get initialized to 0 and increased to 1 every time the function newLecturer() is called. That's why sum always smaller than MAX_LECTURER (1<3).
You need to use class variable numLecturers like in duffymo answer above.

Java values of toString() not printing

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

logResponse Exception in thread "main" java.lang.NullPointerException

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];

How to fix a Null Pointer Exception upon string retrieval - hash table

class Item
{
private int address;
private String itemString;
public Item(String item)
{
separate(item);
}
public void separate(String string)
{
StringTokenizer st = new StringTokenizer(string);
itemString = st.nextToken();
if(st.hasMoreTokens())
{
address = Integer.parseInt(st.nextToken());
}
else
{
address = -1;
}
}
public String getKey()
{
return itemString;
}
public int getAddress()
{
return address;
}
public void illegitimize()
{
itemString = "*del";
address = -1;
}
}
class HashTable
{
private Item[] hashArray;
private int arraySize;
public HashTable(int size)
{
arraySize = size;
hashArray = new Item[arraySize];
}
public int hash(Item item)
{
String key = item.getKey();
int hashVal = 0;
for(int i=0; i<key.length(); i++)
{
int letter = key.charAt(i) - 96;
hashVal = (hashVal * 26 + letter) % arraySize;
}
return hashVal;
}
public void insert(Item item)
{
int hashVal = hash(item);
while(hashArray[hashVal] != null &&
!(hashArray[hashVal].getKey().contains("*")))
{
hashVal++;
hashVal %= arraySize;
}
String keyAtHashVal = hashArray[hashVal].getKey();
String itemKey = item.getKey();
if(!keyAtHashVal.equals(itemKey))
{
hashArray[hashVal] = item;
System.out.println(item.getKey() + " inserted into the table at "
+ "position " + hashVal);
}
else
{
System.out.println("Error: " + item.getKey() + " already exists "
+ "at location " + hashVal);
}
}
public Item find(Item item)
{
int hashVal = hash(item);
while(hashArray[hashVal] != null)
{
if(hashArray[hashVal].getKey().equals(item.getKey()))
{
System.out.println(item.getKey() + " found at location "
+ hashVal + " with address " + item.getAddress());
return hashArray[hashVal];
}
hashVal++;
hashVal %= arraySize;
}
System.out.println("Error: " + item.getKey() + " not found in the "
+ "table");
return null;
}
}
public class HashTableMain
{
public static void main(String[] args) throws Exception
{
File file = new File(args[0]);
Scanner input = new Scanner(file);
Item currentItem;
String currentItemsKey;
int currentItemsAddress;
HashTable table = new HashTable(50);
while(input.hasNextLine())
{
currentItem = new Item(input.nextLine());
currentItemsKey = currentItem.getKey();
currentItemsAddress = currentItem.getAddress();
if(currentItemsAddress > 0)
{
table.insert(currentItem);
}
else
{
table.find(currentItem);
}
}
}
}
The title pretty much explains it. I get a null pointer when the insert() method attempts to retrieve the key of the first item I feed it from the file. I figure this has something to do with the way I retrieve store the string but I cannot identify the problem.
The records inside the file will be in this format:
george
stacy 112
patrick 234
angelo 455
money 556
kim
chloe 223
If there is a number in the line I need to hash the item into the array at the appropriate location. If there is no number I need to search for the key (the string at the beginning of each line).
Edit: added find function. I left out anything I didn't think you needed to help me. If you need anything else let me know.
The problem seems to be at
String keyAtHashVal = hashArray[hashVal].getKey();
in the HashTable.insert() . Your hashArray[hashVal] may not have an object in it leading to a null pointer. You could do a null check.
Item existingItem = hashArray[hashVal];
if(existingItem==null) {
//do appropriate code
} else {
//do your stuff
}
BTW, StringTokenizer is deprecated and is only there for compatibility purposes. You could use the String.split() method.
Plus instead of HashTable , you can use the HashMap if you are not aware of it
String keyAtHashVal = hashArray[hashVal].getKey();
The problem is is that hashArray[hashVal] is always going to be null because you probe for a null space in a previous statement. I suspect that it should be moved inside the while() loop and used there.

Categories

Resources