Just started taking Java 2, and it has been over 6-7 months since I've taken Java 1 and done much programming at all, so please be kind if I did something dumb
The majority of the three classes below are for a previous assignment where you took a listing from the book and had to add a method called getMax() that returns the value of the highest key in the array, or -1 if the array is empty.
This part worked fine.
For the next part(the part I am having trouble with) we had to modify the assignment so that the item with the highest key is not only returned by the method, but also removed from the array.
To do this I tried:
public long removeMax(PrintWriter pw)
{
long maxIndex;
maxIndex = getMax();
delete(maxIndex);
return maxIndex;
}
But the maxIndex = getMax(); and delete(maxIndex); are giving me errors and I'm not quite sure why. Although I'm convinced I'm just making a small mistake due to being rusty at programming.
The error it is giving me is actual and formal argument lists differ in length. I tried changing and switching things around but no matter what I did nothing seemed to work.
Below are the Employee, HighArrayObject and Project21Rev(class where getMax and removeMax are) classes in full.
public class Employee
{
protected int empNo; // employee number
protected String ssno; // social security number
protected String lastName; // Last name
protected String firstName; // First name
//This constructor initializes the variables
public Employee(int eNo, String ssn, String lName, String fName)
// aliases are used in the function header
{
empNo = eNo; // the alias is assigned to the actual value
ssno = ssn;
lastName = lName;
firstName = fName;
}
// Make a no argument constructor as well
public Employee()
{
empNo = 0;
ssno = "";
lastName = "";
firstName = "";
}
/**
The copy constructor initializes the object
as a copy of another Employee object
#param object2 The object to copy
*/
public Employee(Employee object2)
{
empNo = object2.empNo;
ssno = object2.ssno;
lastName = object2.lastName;
firstName = object2.firstName;
}
// The set method sets a value for each field
public void set(int eNo, String ssn, String lName, String fName)
// aliases are used in the function header
{
empNo = eNo; // the alias is assigned to the actual value
ssno = ssn;
lastName = lName;
firstName = fName;
}
// the getKey method returns the employee number
public int getKey()
{ return empNo; }
// the setKey method sets the employee number
public void setKey(int id)
{ empNo = id; }
// toString method
// returns a string containing the instructor information
public String toString()
{
// Create a string representing the object.
String str = "Employee Number: " + empNo +
"\nSocial Security Number: " + ssno +
"\nLast Name: " + lastName +
"\nFirst Name: " + firstName;
// Return the string;
return str;
}
}
Start of next class
import java.io.*;
class HighArrayObject
{
protected Employee[] emp;
protected int nElems;
public HighArrayObject(int max) // constructor
{
emp = new Employee[max];
nElems = 0;
}
// The createEmployees method creates an Employee object
// for each element of the array
public static void createEmployees(Employee[] emp, int maxsize)
{
int empNo;
String ssno;
String lastName;
String firstName;
// Create the employees
for(int index = 0; index < emp.length; index++)
{
// Get the employee data
emp[index] = new Employee();
}
}
public boolean find(long searchKey, PrintWriter pw)
{
System.out.println("Trying to find item with employee number " + searchKey);
pw.println("Trying to find item with employee number " + searchKey);
int j;
for(j=0; j<nElems; j++)
if(emp[j].empNo == searchKey) // == ok since empNo is a primative
break; // exit loop before end
if(j == nElems) // gone to end?
return false;
else
return true; // no, found it
} // end find()
public void insert(int eNo, String sNo, String lName, String fName, PrintWriter pw)
{
System.out.println("Inserting employee with employee number " + eNo);
pw.println("Inserting employee with employee number " + eNo);
Employee temp = new Employee();
temp.empNo = eNo;
temp.ssno = sNo;
temp.lastName = lName;
temp.firstName = fName;
emp[nElems] = temp;
nElems++;
}
public boolean delete(long value, PrintWriter pw)
{
System.out.println("Deleting employee number " + value);
pw.println("Deleting employee number " + value);
int j;
for(j=0; j < nElems; j++) // look for it
if(value == emp[j].empNo)
break; // can't find it
if(j==nElems)
return false;
else // found it
{
for(int k=j; k<nElems; k++) // move higher ones down
{
emp[k]=emp[k+1];
}
nElems--; // decrement size
return true;
}
} // end delete
public void display(PrintWriter pw)
{
System.out.println("The array of employees is: ");
pw.println("The array of employees is: ");
for(int j=0; j<nElems; j++)
{
System.out.println(emp[j].empNo + " " + emp[j].ssno + " "
+ emp[j].lastName + " " + emp[j].firstName);
pw.println(emp[j].empNo + " " + emp[j].ssno + " "
+ emp[j].lastName + " " + emp[j].firstName);
} // end for
} // end delete
} // end HighArrayObject
Start of next class
import java.io.*;
public class Project21Rev extends HighArrayObject //reference Gaddis p.658
{
public Project21Rev(int max) // subclass constructor
{
super(max); // call superclass constructor
}
public void getMax(PrintWriter pw) // new functionality as required by the assignment
{
int maxIndex = -1; // not found yet
if(nElems == 0)
System.out.println("Number of elements is 0");
else
{
int max = emp[0].empNo; // assume the first value is the largest
maxIndex = 0;
for (int i = 1; i < nElems; i++) //now check the rest of the values for largest
{
if(emp[i].empNo > max)
{
maxIndex = i;
}
}
System.out.println("The largest value is " + emp[maxIndex].empNo + " " + emp[maxIndex].ssno + " " + emp[maxIndex].lastName + " " + emp[maxIndex].firstName);
pw.println("The largest value is " + emp[maxIndex].empNo + " " + emp[maxIndex].ssno + " " + emp[maxIndex].lastName + " " + emp[maxIndex].firstName);
System.out.println("at location " + maxIndex);
pw.println("at location " + maxIndex);
}
}
public long removeMax(PrintWriter pw)
{
long maxIndex;
maxIndex = getMax();
delete(maxIndex);
return maxIndex;
}
// modified find method follows
public void find( int searchKey, PrintWriter pw)
{
System.out.println("Trying to find item with employee number " + searchKey);
pw.println("Trying to find item with employee number " + searchKey);
int j;
Boolean found = false;
for(j=0; j < nElems; j++)
if(emp[j].empNo == searchKey)
{
found = true;
System.out.println("Found " + emp[j].empNo + " " + emp[j].ssno + " " + emp[j].lastName + " " + emp[j].firstName);
pw.println("Found " + emp[j].empNo + " " + emp[j].ssno + " " + emp[j].lastName + " " + emp[j].firstName);
System.out.println("at location " + j);
pw.println("at location " + j);
}
if(found == false)
{
System.out.println(searchKey + " Not found");
pw.println(searchKey + " Not found");
}
}
}
class Project21RevApp
{
public static void main(String[] args) throws IOException
{
// set up printer output file
PrintWriter pw = new PrintWriter(new BufferedWriter
(new FileWriter("output21.dat")));
int maxSize = 100; // array size
Project21Rev arr; // reference to array
arr = new Project21Rev(maxSize); // create the array
arr.insert(77,"A","B","C",pw);
arr.insert(99,"D","E","F",pw);
arr.insert(44,"G","H","I",pw);
arr.insert(55,"J","K","L",pw);
arr.insert(22,"M","N","O",pw);
arr.insert(88,"P","Q","R",pw);
arr.insert(11,"S","T","U",pw);
arr.insert(00,"V","W","X",pw);
arr.insert(66,"Y","Z","AA",pw);
arr.insert(33,"BB","CC","DD",pw);
arr.display(pw); // display items
int searchKey = 35; // search for item
arr.find(searchKey, pw);
searchKey = 22; // search for item
arr.find(searchKey, pw);
arr.delete(00, pw); // delete 3 items
arr.delete(55, pw);
arr.delete(99, pw);
arr.display(pw); // display items again
// new functionality follows
arr.getMax(pw);
pw.close();
} // end main()
} // end class Project21RevApp
Well, the error message actually tells you exactly what's wrong.
Your method delete() accepts two parameters:
public boolean delete(long value, PrintWriter pw) {
// ...
}
You are trying to call it with only one:
delete(maxIndex);
To fix the error, pass the right amount and types of parameters.
Hymm there are too many wrong things. Start by learning what a Method is and how you call it. You are trying to call your method
public void getMax(PrintWriter pw){..}
with
maxIndex = getMax();
Now you see when you deffined that method you told it with VOID that it should return nothing. But it requires a PrintWriter Object. You had the right idea when you created your:
public long removeMax(PrintWriter pw)
you see that method should receive such variable/object and it will be "pw".
So the right way to call your method would be
getMax(pw);
and if you want it to return something you really should just read a bit more about java and the way methods work.
The other big problem is that you are talking about a LIST (abstract data type) but in the code I see
protected Employee[] emp;
Witch is not at all a list but just a simple Array. There is a big difference. If the requirements are that you have an actual java/programming list, then there is no such thing in the Program. It's just an Array that looks like a general list of things, but that is called an Array in most programming languages. Perhaps your teacher makes no difference.
This is not a complete solution but there are too many things to fix and the code is too big for whatever it's suppose to do. Don't get stressed, just continue to read about Java from whatever source you got. Keep in mind you are working with Arrays not a lists in that code and you need to learn some basic information about the language.
Related
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.
I want to create a program which displays current staff in the ArrayList before asking the user for input of a payroll number they'd like to remove. User then should input the payroll number of one of the three staff members and press enter. Upon pressing enter, the program should remove that particular staff member from the array list and display the entire list again (missing out the staff member they've deleted obviously). If the user no longer wishes to remove any payroll numbers, the payroll number entry should be 0 and should then display the contents of the list again.
The problem I'm having is with the remove part.
I've been recommended of two ways of achieving this:
This 'search' method should return either the position within the ArrayList (so that remove(<index>) may be used) or a reference to the object (so that remove(<objectRef>) may be used). If the staff member is not found, then the search method should return -1 (if remove(<index>) is being used) or null (if remove(<objectRef>) is being used).
However I am not sure how to implement this in Java.
Here is my file structure:
ArrayListTest.java
import java.util.*;
import personnelPackage.Personnel;
public class ArrayListTest
{
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args)
{
long searchQuery;
ArrayList<Personnel> staffList = new ArrayList<Personnel>();
Personnel[] staff =
{new Personnel(123456,"Smith","John"),
new Personnel(234567,"Jones","Sally Ann"),
new Personnel(999999,"Black","James Paul")};
for (Personnel person:staff)
staffList.add(person);
do
{
showDisplay(staffList);
System.out.print("\nPlease enter a payroll number to search: ");
searchQuery = keyboard.nextLong();
searchForPayrollNumber(staffList, searchQuery);
}while(!(searchQuery == 0));
}
private static void showDisplay(ArrayList<Personnel> staffList)
{
System.out.print("\n------------- CURRENT STAFF LIST -------------\n");
for (Personnel person : staffList)
{
System.out.println("Payroll number: " + person.getPayNum());
System.out.println("Surname: " + person.getSurname());
System.out.println("First name(s): " + person.getFirstNames() + "\n");
}
}
public static void searchForPayrollNumber(ArrayList<Personnel> staffList, long searchQuery)
{
long index = staffList.indexOf(searchQuery);;
for (Personnel person: staffList)
{
if (person.getPayNum() == searchQuery)
{
System.out.print("\n------------- Staff member found and removed! -------------");
System.out.println("\n\nFirst Name(s): " + person.getFirstNames());
System.out.println("\nSurname: " + person.getSurname());
System.out.print("\n-----------------------------------------------");
staffList.remove(index);
return;
}
}
System.out.print("\n------------- No staff members found. Program terminated -------------");
return;
}
}
Personnel.java (in its own package named personnelPackage)
package personnelPackage;
public class Personnel
{
private long payrollNum;
private String surname;
private String firstNames;
public Personnel(long payrollNum, String surname, String firstNames)
{
this.payrollNum = payrollNum;
this.surname = surname;
this.firstNames = firstNames;
}
public long getPayNum()
{
return payrollNum;
}
public String getSurname()
{
return surname;
}
public String getFirstNames()
{
return firstNames;
}
public void setSurname(String newName)
{
surname = newName;
}
}
Consider using Iterator for search and removal:
Iterator<Personnel> i = staffList.iterator();
while (i.hasNext()) {
Personnel p = i.next();
if (p.getPayNum() == searchQuery) {
// print message
i.remove();
return p;
}
}
return null;
If using List#remove() is strictly required, return found personnel p and call if (p != null) staffList.remove(p):
public static Personnel searchByPayNum(List<Personnel> ps, long num) {
for (Personnel p : ps) {
if (p.getPayNum() == num)
return p;
}
return null;
}
And in caller code:
Personnel p = searchByPayNum(staffList, query);
if (p != null) {
// log
staffList.remove(p);
}
public static long searchForPayrollNumber(ArrayList<Personnel> staffList, long searchQuery) {
//long index = staffList.indexOf(searchQuery);
for(int i = 0; i < staffList.size(); i++) {
if (staffList.get(i).getPayNum() == searchQuery) {
System.out.print("\n------------- Staff member found and removed! -------------");
System.out.println("\n\nFirst Name(s): " + staffList.get(i).getFirstNames());
System.out.println("\nSurname: " + staffList.get(i).getSurname());
System.out.print("\n-----------------------------------------------");
//staffList.remove(i);
return i;
}
}
System.out.print("\n------------- No staff members found. Program terminated -------------");
return -1;
}
Your search method shouldn't return void. It should return int or long instead,
public static long searchForPayrollNumber(ArrayList<Personnel> staffList, long searchQuery)
{
int index = -1;
for (int i = 0; i < staffList.size(); i++){
if(staffList.get(i).getPayNum() == searchQuery){
index = i;
System.out.print("\n------------- Found Staff member at position " + index + " in the list");
break;
}
}
if (index != -1){
staffList.remove(index);
System.out.print("\n------------- Removed the staff member");
}
return index;
}
Last approach returned the index. Now when you want to return the object:
public static long searchForPayrollNumber(ArrayList<Personnel> staffList, long searchQuery)
{
Personnel p = null;
for (int i = 0; i < staffList.size(); i++){
if(staffList.get(i).getPayNum() == searchQuery){
p = staffList.get(i);
break;
}
}
staffList.remove(p);
return p;
}
You must know that after removing it from the list, It will shift any subsequent elements to the left (subtracts one from their indices).
Also, just a suggestion:
Instead of
Personnel[] staff =
{new Personnel(123456,"Smith","John"),
new Personnel(234567,"Jones","Sally Ann"),
new Personnel(999999,"Black","James Paul")};
Why not
staffList.add(new Personnel(123456,"Smith","John"));
staffList.add(new Personnel(234567,"Jones","Sally Ann"));
staffList.add(new Personnel(999999,"Black","James Paul"));
This is just an advice. Since searching and removing are your primary goals, ArrayList is not the right collection to use.
Create a Hashmap with ID as key and Personnel object as value. This will help in identifying the Personnel in O(1) time and removal as well.
ArrayList should be used only when you know the index to read value. It then does that in O(1). If not, it is O(n) and not as efficient as HashMap.
I try to determine the error since yesterday, but did not find him. All I know is where he must be placed approximately. But now to the topic.
For my app I have created a separate class with the name Player. Now if I make an ArrayList with this class, a newly added object overwrites all existing objects. So:
ArrayList empty -> Player is stored in ArrayList
ArrayList already contains a Player -> ArrayList now contains the newest Player instance two times
etc.
Here is my code corresponding to:
Player Object
public Player(String n, int m, int t) {
name = n;
money = m;
tip = t;
}
public String getName() {
return this.name;
}
public int getMoney() {
return this.money;
}
public int getTip() {
return this.tip;
}
public String toString() {
return this.name + "\n Tipp: " + this.tip + " | Einsatz: " + this.getMoney() + " ,- €";
}
Creating the ArrayList
public void addPlayertoEvent(String name, int money, int tip) {
Player p = new Player(name, money, tip);
playerList.add(p);
playerListString.add(p.toString());
lvPlayers.setAdapter(null);
ArrayAdapter<String> playerAdapter = new ArrayAdapter<String>(AddEventActivity.this, R.layout.list_items, playerListString);
lvPlayers.setVisibility(View.VISIBLE);
lvPlayers.setAdapter(playerAdapter);
etTip.setText("");
etName.setText("");
for(int i = 0; i < playerList.size(); ++i) {
Log.e("AL", "" + playerList.get(i).getName() + " " + playerList.get(i).getMoney() + " " + playerList.get(i).getTip());
}
}
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;
}
}
}
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.