sorting method crashes when running - java

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.

Related

Displaying the names and times of the first and second winners of a marathon

Locked for 9084 days. There are disputes about this question’s content being resolved at this time. It is not currently accepting new answers or interactions.
I would like your help here guys
/**
* In this assignment I am supposed to display the names and times of the first and second winners (2 best times) of a marathon
* But I am struggling with the second one
*/
public class MitAssignment3Chapter7 {
public static void main(String args[]){
String runners[] = {"Gene","Elvis","Presley","Felicity","Welcome"};
int[] timeInMinutes = {40,50,76,56,62};
int index = 0;
int a = 0;
int first = timeInMinutes[1];
for (a = 0 ; a < timeInMinutes.length; a++){
if ( first > timeInMinutes[a]){
index = a;
first = timeInMinutes[index];
}
// if (first < timeInMinutes[a] && timeInMinutes[a]) Trying to do the second here
}
System.out.println("The winner of the marathon is: "+runners[index]+" with "+timeInMinutes[index]+" minutes");
}
}
Locked for 9084 days. There are disputes about this answer’s content being resolved at this time. It is not currently accepting new interactions.
using other collections would be easy.. but you can do it with simple arrays also.. not only second one, you can find all ranks of runners by sorting arrays.. check this code..
public static void main(String args[]) {
String runners[] = { "Gene", "Elvis", "Presley", "Felicity", "Welcome" };
int[] timeInMinutes = { 40, 50, 76, 56, 62 };
int a = 0;
int tempTime = 0;
String tempRunner = "";
for (int i = 0; i < timeInMinutes.length; i++) {
for (int j = i + 1; j < timeInMinutes.length; j++) {
if (timeInMinutes[i] > timeInMinutes[j]) {
tempTime = timeInMinutes[i];
timeInMinutes[i] = timeInMinutes[j];
timeInMinutes[j] = tempTime;
tempRunner = runners[i];
runners[i] = runners[j];
runners[j] = tempRunner;
}
}
}
for (int index = 0; index < runners.length; index++)
System.out.println("Rank " + (index+1) + ": " + runners[index] + " with " + timeInMinutes[index] + " minutes");
}
You can find the winner first, after you had found out winner, take winner out of your time array and find the fastest people in your current array, it will be the second player.
You can create a new class to hold result time and the name. Implement compareTo method for this class. Populate new List with all the results and sort the one. Now it's possible to get any Nth result(time and name).
static class Result implements Comparable<Result> {
private final int time;
private final String name;
Result(int time, String name) {
this.time = time;
this.name = name;
}
int getTime() { return time; }
String getName() { return name; }
#Override
public int compareTo(Result o) {
return Integer.compare(time, o.time);
}
}
public static void main(String args[]){
String runners[] = {"Gene","Elvis","Presley","Felicity","Welcome"};
int[] timeInMinutes = {40,50,76,56,62};
List<Result> results = new ArrayList<>(runners.length);
for (int i = 0; i < runners.length; i++) {
results.add(new Result(timeInMinutes[i], runners[i]));
}
Collections.sort(results);
Result second = results.get(1);
System.out.println("Second winner: " + second.getName() + "; Time: " + second.getTime());
}

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

Insertion sort not working

The sortYears() method should sort the movies by year of release in descending order. It compiles fine, but does not change the order of the movies in the array sorted. What is the least uncomplicated way to fix make it work? Thanks.
Movie2 class:
public class Movie2 implements Comparable<Movie2>
{
// instance variables
private String title;
private int year;
private String studio;
public Movie2(String title, int year, String studio)
{
// initialise instance variables
this.title = title;
this.year = year;
this.studio = studio;
}
public String toString()
{
String listing;
listing = title + ", " + year + ", " + studio;
return listing;
}
public void setTitle(String title)
{
this.title = title;
}
public String getTitle()
{
return title;
}
public void setYear(int year)
{
this.year = year;
}
public int getYear()
{
return year;
}
public void setStudio(String studio)
{
this.studio = studio;
}
public String getStudio()
{
return studio;
}
public int compareTo(Movie2 obj)
{
if (title.equals(obj.title))
return -1;
else if (title == obj.title)
return 0;
else
return 1;
}
}
TestMovie2 class:
public class TestMovie2
{
public static void main(String[] args)
{
Movie2[] myMovies = new Movie2[10];
Movie2[] sorted = new Movie2[10];
myMovies[0] = new Movie2("The Muppets Take Manhattan", 2001, "Columbia Tristar");
myMovies[1] = new Movie2("Mulan Special Edition", 2004, "Disney");
myMovies[2] = new Movie2("Shrek 2", 2004, "Dreamworks");
myMovies[3] = new Movie2("The Incredibles", 2004, "Pixar");
myMovies[4] = new Movie2("Nanny McPhee", 2006, "Universal");
myMovies[5] = new Movie2("The Curse of the Were-Rabbit", 2006, "Aardman");
myMovies[6] = new Movie2("Ice Age", 2002, "20th Century Fox");
myMovies[7] = new Movie2("Lilo & Stitch", 2002, "Disney");
myMovies[8] = new Movie2("Robots", 2005, "20th Century Fox");
myMovies[9] = new Movie2("Monsters Inc.", 2001, "Pixar");
System.out.println(" Movies (before change) ");
System.out.println("______________________________");
System.out.println();
printMovies(myMovies);
System.out.println();
System.out.println();
for (int i = 0; i < myMovies.length; i++)
{
int next = myMovies[i].getYear();
int insertIndex = 0;
int k = i;
while (k>0 && insertIndex == 0)
{
if (next > sorted[k-1].getYear())
{
insertIndex = k;
}
else
{
sorted[k] = sorted[k-1];
}
k--;
}
sorted[insertIndex].setYear(next);
}
sortYears(myMovies, sorted);
System.out.println(" Sorted by year - descending");
System.out.println("______________________________");
System.out.println();
printMovies(sorted);
System.out.println();
System.out.println();
public static void printMovies(Movie2[] sorted)
{
for(int i = 0; i < sorted.length; i++)
System.out.println(sorted[i]);
}
public static void sortYears(Movie2[] myMovies, Movie2[] sorted)
{
for ( int i = 0 ; i < myMovies.length ; i++ )
{
Movie2 next = myMovies[ i ];
int insertindex = 0;
int k = i;
while ( k > 0 && insertindex == 0 )
{
if ( next.getYear() > sorted[k-1].getYear() )
{
insertindex = k;
}
else
{
sorted[ k ] = sorted[ k - 1 ];
}
k--;
}
sorted[ insertindex ] = next;
}
You are going about your insertion sort incorrectly. Think about the logic needed to sort from Highest to lowest. This is an insertion sort working with an array, but this works, and can be extrapolated to fit your code.
public static void main(String[] args) {
int [] ar1 = {1, 5, 4, 9, 3, 2, 7, 8, 6, 0};
int temp = 0;
System.out.println ("Unsorted: ");
for (int i = 0; i < ar1.length; i++)
System.out.print (ar1[i] + " ");
for (int i = 1; i < ar1.length; i++) {
temp = ar1[i];
// temp < ar1[j] = Sort in ascending order
for (int j = i - 1; j >= 0 && temp > ar1[j]; j--) {
ar1[j + 1] = ar1[j];
}
ar1[j + 1] = temp;
}
System.out.println ("\nSorted: ");
for (int i = 0; i < ar1.length; i++)
System.out.print (ar1[i] + " ");
}
}

CompareTo bubble sort

I am attempting to sort the values in my program using the Bubble Sort method. I believe that my code in the organisedRoom method is correct. However when I run the code, add some customers and then attempt to sort them, the program crashes. If anyone can please point me in the right direction I would greatly appreciate it.
package test;
import java.io.IOException;
import java.util.Scanner;
public class Test {
private class Customer implements Comparable<Customer>{
private String name;
public Customer(String name) {
this.name = name;
}
//Override to stop the program returning memory address as string
#Override
public String toString() {
return name;
}
#Override
public int compareTo(Customer c) {
return name.compareTo(c.name);
}
}
//Array to store customers
public Customer[] customers;
public Scanner input = new Scanner(System.in);
public Test(int nRooms) throws IOException {
customers = new Test.Customer[nRooms];
System.out.println("Welcome to the Summer Tropic Hotel\n");
chooseOption();
}
final JFileChooser fc = new JFileChooser();
// Call new Hotel with int value to allocate array spaces
public static void main(String[] args) throws IOException {
Test t = new Test(11);
}
// New procedure to return User input and point to next correct method
private String chooseOption() throws IOException {
// Set to null, this will take user input
String choice;
//Menu options
System.out.println("This is the Hotel Menu. Please choose from the following options:\n");
System.out.println("A: " + "This will add a new entry\n");
System.out.println("O: " + "View booked rooms, in order of customers name.\n");
System.out.println("X: " + "Exit the program\n");
// Take user input and assign it to choice
choice = input.next();
// Switch case used to return appropriate method
switch (choice.toUpperCase()) {
case "A" :
System.out.println("");
addCustomer();
return this.chooseOption();
case "O" :
System.out.println("");
organisedRoom();
return this.chooseOption();
case "X":
System.exit(0);
}
return choice;
}
// Add a new customer to the Array
public void addCustomer() throws IOException {
// New variable roomNum
int roomNum = 1;
// Loop
do {
// Take user input as room number matching to array index - 1
System.out.println("Please choose a room from 1 to 10");
roomNum = input.nextInt() - 1;
// If room is already booked print this
if (customers[roomNum] != null) {
System.out.println("Room " + roomNum + 1 + " is not free, choose a different one.\n");
this.addCustomer();
}
// Do until array index does not equal to null
} while (customers[roomNum]!= null);
System.out.println("");
// User input added to array as name replacing null (non case-sensetive)
System.out.println("Now enter a name");
customers[roomNum] = new Customer(input.next().toLowerCase());
// Customer (name) added to room (number)
System.out.println(String.format("Customer %s added to room %d\n", customers[roomNum], roomNum + 1));
}
private void organisedRoom() {
boolean flag = true;
Customer temp;
int j;
while (flag) {
flag = false;
for (j = 0; j < customers.length - 1; j++) {
if (customers[j].compareTo(customers[j+1]) < 0) {
temp = customers[j];
customers[j] = customers[j + 1];
customers[j + 1] = temp;
flag = true;
}
}
}
}
}
I think this is because the initialisation of the array adds null to all the array index places.
The stack trace is as follows:
Exception in thread "main" java.lang.NullPointerException
at test.Test$Customer.compareTo(Test.java:34)
at test.Test.organisedRoom(Test.java:133)
at test.Test.chooseOption(Test.java:83)
at test.Test.chooseOption(Test.java:79)
at test.Test.chooseOption(Test.java:79)
at test.Test.<init>(Test.java:46)
at test.Test.main(Test.java:55)
Java Result: 1
It fails because you create Customer[] which will be initialized with11 null references. If you want to order them all elements in the array will be compared. Which lead into the java.lang.NullPointerException.
Store the Customer in an ArrayList. Then you should be able to prevent this error.
edit
If you really need to stick as close as possible to your current code. The following would fix your sorting. (don't use this solution for a real life project)
private void organisedRoom() {
for (int i = customers.length - 1; i > 0; i--) {
for (int j = 0; j < i; j++) {
if (customers[j + 1] == null) {
continue;
}
if (customers[j] == null ||customers[j + 1].compareTo(customers[j]) < 0) {
Customer temp = customers[j + 1];
customers[j + 1] = customers[j];
customers[j] = temp;
}
}
}
System.out.println("show rooms: " + Arrays.toString(customers));
}
edit 2
To keep most of your current code, you might store the room in the Customer instance (which I personally would not prefer).
// change the constructor of Customer
public Customer(String name, int room) {
this.name = name;
this.room = room;
}
// change the toString() of Customer
public String toString() {
return String.format("customer: %s room: %d", name, room);
}
// store the Customer like
customers[roomNum] = new Customer(input.next().toLowerCase(), roomNum);
Your implementation of Bubble Sort is incorrect. It uses nested for loops.
for(int i = 0; i < customers.length; i++)
{
for(int j = 1; j < (customers.length - i); j++)
{
if (customers[j-1] > customers[j])
{
temp = customers[j-1];
customers[j-1] = customers[j];
customers[j] = temp;
}
}
}

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

Categories

Resources