How to get the data from a file into an array? - java

Over the passed couple of hours I have been working on an assigment with no luck in figuring it out. For reference I am going to post the instructions below and then explain what I have done.
Write a Java class that implements the StringSet interface (see
attached text document). One of your instance variables must be an
array of Strings that holds the data; you may determine what, if any
other instance variables you need. You will also need to implement the
required methods, one or more constructors, and any other methods you
deem necessary. I have also provided a tester class that you should be
able to run your code with.
So far I have created an implementation of the interface named MyStringSet. I have put all of the methods from the interface into my implementation and have written the code to what I think will work. My main problem is that I don't know how to put the data from the main method that is called into an array. The user types in a file and and then it is supposed to return word count and other methods. Since the file is being called from the tester class, I need to store that data into an array or an array list which I have already created. Below I have listed my current implementation and the tester class that I use. Any help is greatly appreciated!
My Implementation:
public class MyStringSet implements StringSet {
String[] myArray = new String [] {};
List<String> myList = Arrays.asList(myArray);
//default constructor
public MyStringSet(){
resize(5);
}
// precondition: larger is larger than current Set size
// postcondition: enlarges Set
public void resize(int larger) {
myArray = Arrays.copyOf(myArray, myArray.length + larger);
}
// postcondition: entry is inserted in Set if identical String
// not already present; if identical entry exists, takes no
// action. Calls resize if necessary
public void insert(String entry) {
Set<String> myArray = new HashSet<String>();
Collections.addAll(myArray, entry);
}
// postcondition: removes target value from Set if target is
// present; takes no action otherwise
public void remove(String target) {
if(target != null){
int n = 0;
int index = n;
for(int i = index; i < myArray.length - 1; i++) {
myArray[i] = myArray[i+1];
}
}
}
// precondition: Set is not empty
// postcondition: A random String is retrieved and removed from
// the Set
public String getRandomItem () {
String s = "String is Empty";
if (myArray != null) {
int rnd = new Random().nextInt(myArray.length);
return myArray[rnd];
}
else {
return s ;
}
}
// precondition: Set is not empty
// postcondition: the first item in the Set is retrieved and
// removed from the Set
public String getFirstItem () {
String firstItem = myList.get(0);
return firstItem;
}
// postcondition: returns true if target is present, false
// if not
public boolean contains(String target) {
if (target == null) {
return false;
}
else {
return true;
}
}
// postcondition: returns true if Set is empty, false if not
public boolean is_empty( ) {
if(myArray == null){
return true;
}
else {
return false;
}
}
// postcondition: returns total number of Strings currently in set
public int inventory() {
int total = myList.size();
return total;
}
// postcondition: returns total size of Set (used & unused portions)
public int getCapacity( ) {
int capacity = myArray.length;
return capacity;
}
}
Tester class:
public class SetTester
{
public static void main(String [] args) {
StringSet words = new MyStringSet();
Scanner file = null;
FileInputStream fs = null;
String input;
Scanner kb = new Scanner(System.in);
int wordCt = 0;
boolean ok = false;
while (!ok)
{
System.out.print("Enter name of input file: ");
input = kb.nextLine();
try
{
fs = new FileInputStream(input);
ok = true;
}
catch (FileNotFoundException e)
{
System.out.println(input + " is not a valid file. Try again.");
}
}
file = new Scanner(fs);
while (file.hasNext())
{
input = file.next();
words.insert(input);
System.out.println("Current capacity: " + words.getCapacity());
wordCt++;
}
System.out.println("There were " + wordCt + " words in the file");
System.out.println("There are " + words.inventory() + " elements in the set");
System.out.println("Enter a value to remove from the set: ");
input = kb.nextLine();
while (!words.contains(input))
{
System.out.println(input + " is not in the set");
System.out.println("Enter a value to remove from the set: ");
input = kb.nextLine();
}
words.remove(input);
System.out.println("There are now " + words.inventory() + " elements in the set");
System.out.println("The first 10 words in the set are: ");
for (int x=0; x<10; x++)
System.out.println(words.getFirstItem());
System.out.println("There are now " + words.inventory() + " elements in the set");
System.out.println("5 random words from the set are: ");
for (int x=0; x<5; x++)
System.out.println(words.getRandomItem());
System.out.println("There are now " + words.inventory() + " elements in the set");
}
}

main problem is that I don't know how to put the data from the main method that is called into an array
You're doing that correctly already, following this simple example
StringSet words = new MyStringSet();
words.insert("something");
However, the contents of the insert method seem incorrect 1) you never check for identical values 2) never resizing 3) Collections.addAll doesn't do what you want, most likely
So, with those in mind, and keeping an array, you should loop over it, and check where the next non-null, non-identical value would be placed
// postcondition: entry is inserted in Set if identical String
// not already present; if identical entry exists, takes no
// action. Calls resize if necessary
public void insert(String entry) {
int i = 0;
while (i < myArray.length && myArray[i] != null) {
if (myArray[i].equals(entry)) return; // end function because found matching entry
i++;
}
if (i >= myArray.length) {
// TODO: resize()
insert(entry); // retry inserting same entry into larger array
}
// updates the next non-null array position
myArray[i] = entry;
}
As far as displaying the MyStringSet class goes, to see the contents of the array, you'll want to add a toString method

Related

Java - accumulator variable not incrementing after each loop iteration

When a car departs, the number of times a car was moved inside the garage should be shown along with the car plate. The output I am currently getting shows everything just fine, but the number of moves remains at 0 for all cars. I am having trouble figuring how to increment the variable and show the accumulated value in the output. How can I fix it?
Car class
package garagetester;
public class Car
{
private String licensePlate;//stores the license plate of the car as a String
private int movesCount = 0;//stores the number of times the car has been
//moved
public Car(String licensePlate)//builds a Car object with
{
this.licensePlate = licensePlate;
}
public String getLicensePlate() {
return licensePlate;
}
public int getMovesCount() {
return movesCount;
}
public void incrementMovesCount(int movesCount) {
movesCount++;
}
}//end of Car class
Garage Class
package garagetester;
public class Garage {
private Car[] garage; //array, stores Car objects
private final int LIMIT = 10; //determines length of the garage array
private int count;//number of cars in garage
public Garage() {
garage = new Car[LIMIT];
//creates an array of 10 elements
//first index = 0, last index = 9
public String arrive(Car newCar) {
String str = ""; //stores the result of the ARRIVE operation
/* If the garage is empty, the first car to arrive is parked in
the first empty spot closest to the exit*/
if (count != LIMIT) {
garage[count] = newCar;
count++;
str = newCar.getLicensePlate() + " has been parked";
} else {
str = "Sorry, " + newCar.getLicensePlate() + " the garage is full.";
}
return str;
}//end of arrive()
public String depart(String plate) {
String str = ""; //stores the result of executing the operation
int moves =0; //stores the number of times a car has been moved
boolean found = false; //flag
for (int i = 0; i < count - 1; i++) //for all elements in the array
{
//check if car with that plate number is in the garage
if (plate.equals(garage[i].getLicensePlate()))
{
found = true; //car has been found
if (found)//if found=true
{
//for all cars ahead of it
for (int j = i + 1; j < count; j++)//check if count or count-1
{
moves += garage[j].getMovesCount();
garage[j].incrementMovesCount(moves);
}
//for all cars behind it
for (int k = i; k > 0; k--) //or k=i-1, check when debugging
{
//move all cars behind it one position up
garage[k] = garage[k - 1];
}
str = plate + " has departed." + "it has been moved " + moves
+ " times. ";
count--; //decrease the number of cars in the garage by 1
}
else
{
str = "Sorry " + plate + " is not in the garage.";
}
}
}//end of for loop
return str;//prints the value stored in str
} //end of depart()
} //end of Garage class
Garage Tester Class
package garagetester;
import java.io.*;
import java.util.Scanner;
public class GarageTester
{
public static void main(String[] args) throws FileNotFoundException, IOException
{
//Initializes an array of 10 Car objects
Garage newGarage = new Garage();
//initializes a Scanner object to read data from file
Scanner scan = new Scanner(new File("garage.txt"));
//while there is tokens in the file
while (scan.hasNext())
{
String plate = scan.next();//stores the plate number read from file
String action = scan.next();//stores the action read from file
//evaluate action
switch (action) {
//if action has the value "ARRIVE"
case "ARRIVE":
Car aCar = new Car(plate);//create a Car object
System.out.println(newGarage.arrive(aCar));//call arrive method
break;
//if action has the value "DEPART"
case "DEPART":
System.out.println(newGarage.depart(plate));//call the depart method
break;
} //end of switch case
}//end of while
}//end of main()
} //end of GarageTester class
In your increment method should be like this in Car.java;
public void incrementMovesCount() {
this.movesCount++;
}
Also fix the other usage of this method. There is no need to send any data to new value. Car object has a movesCount field. That means , it can increment the movesCount itself.
If you dont want to change method signature , use this;
public void incrementMovesCount(int newMovesCount) {
this.movesCount = newMovesCount; //--newMovesCount refers to your calculation
}
but be carefull when using the last solution, because you are sending param as ;
moves += garage[j].getMovesCount(); //this moves never set to 0. Just equal to zero in the first iteration.
garage[j].incrementMovesCount(moves);
This is wrong i think. Because i suppose you wants to increment all of car's position. If you wants to apply first solution of my post, just fix compile error. But if you wants to apply second solution, just change this part like ;
garage[j].incrementMovesCount(garage[j].getMovesCount()+1);
Your parameter movesCount is shadowing the class member movesCount. In the following mutator:
public void incrementMovesCount(int movesCount) {
// movesCount++; --> this is incrementing the parameter
// either remove the parameter `movesCount` from this mutator
// since it's not being used, or do the following
this.movesCount++; // --> this refers to the class member movesCount
}

Setting an array of objects and searching through it for variables

I've been struggling with a method that is meant to search through an array of objects and return a specific value.In my driver class, I read the periodic table csv file and split the variables read in each line send it to an object of the Element class. In my periodic table class, I create an array of Element objects that is meant to hold each element that is read from the driver. My current "findElement" method results in a nullpointer exception and I'm not sure if my array of objects is doing exactly what I want it to. Feel free to throw out suggestions. Below are my classes:(i went back to a driver only program)
Driver:This class opens an input file and splits a line into 7 different variables which are then sent to an Element class object.
public class PeriodicTableDriver
{
public static void main(String[] args)
{
Scanner keyboard= new Scanner(System.in);
Scanner inputStream=null;
String elementName="";
String atomicNumber="";
String symbol="";
double boilingPoint=0;
double meltingPoint=0;
double density=0;
double molecularWeight=0;
int choice=0;
String fileName1= "PeriodicTableData.csv";
String fileName2= "MolecularWeightInput.txt";
PeriodicTable periodicTable= new PeriodicTable();
try
{
inputStream=new Scanner(new File(fileName1));
}
catch(FileNotFoundException e){
System.out.println("Error opening the file.");
System.exit(0);
}
int count=0;
String title=inputStream.nextLine();
while(inputStream.hasNext()){
String periodicInfo=inputStream.nextLine();
String[] PeriodicTableData= periodicInfo.split(",");
elementName=PeriodicTableData [0];
atomicNumber= PeriodicTableData [1];
symbol= PeriodicTableData [2];
if (PeriodicTableData[3].equals(""))
boilingPoint = 0;
else
boilingPoint = Double.parseDouble(PeriodicTableData[3]);
if (PeriodicTableData[4].equals(""))
meltingPoint = 0;
else
meltingPoint = Double.parseDouble(PeriodicTableData[4]);
if (PeriodicTableData[5].equals(""))
density = 0;
else
density = Double.parseDouble(PeriodicTableData[5]);
if (PeriodicTableData[6].equals(""))
molecularWeight = 0;
else
molecularWeight = Double.parseDouble(PeriodicTableData[6]);
count++;
Element element= new Element(count,elementName,atomicNumber,symbol,boilingPoint,meltingPoint,density,molecularWeight);
periodicTable.readPeriodicTableInfo(element);
periodicTable.displayElement(symbol);
}
try
{
inputStream=new Scanner(new File(fileName2));
}
catch(FileNotFoundException e){
System.out.println("Error opening the file.");
System.exit(0);
}
while(inputStream.hasNextLine()){
}
}
}
Element class: holds all of the variables read from the driver and has a toString method for formatting them
public class Element
{
String elementName;
String atomicNumber;
String symbol;
double boilingPoint;
double meltingPoint;
double density;
double molecularWeight;
int count;
public Element(int count, String elementName, String atomicNumber, String symbol,
double boilingPoint, double meltingPoint, double density,
double molecularWeight)
{
super();
this.count=count;
this.elementName = elementName;
this.atomicNumber = atomicNumber;
this.symbol = symbol;
this.boilingPoint = boilingPoint;
this.meltingPoint = meltingPoint;
this.density = density;
this.molecularWeight = molecularWeight;
}
public String toString(){
String element = "Element name: " + elementName
+ "\nAtomic Number: " + atomicNumber
+ "\nSymbol: " + symbol;
if (boilingPoint == 0)
{
element = element + "\nBoiling Point: unknown";
}
else
{
element = element + "\nBoiling Point: " + boilingPoint + " K";
}
if (meltingPoint == 0)
{
element = element + "\nMelting Point: unknown";
}
else
{
element = element + "\nMelting Point: " + meltingPoint + " K";
}
if (density == 0)
{
element = element + "\nDensity: unknown";
}
else
{
element = element + "\nDensity: " + density + " g/L";
}
element=element+"\nMolecular Weight: " + molecularWeight + "g/mole";
return element;
}
/**
* #return the elementName
*/
public String getElementName()
{
return elementName;
}
/**
* #return the atomicNumber
*/
public String getAtomicNumber()
{
return atomicNumber;
}
/**
* #return the symbol
*/
public String getSymbol()
{
return symbol;
}
/**
* #return the boilingPoint
*/
public double getBoilingPoint()
{
return boilingPoint;
}
/**
* #return the meltingPoint
*/
public double getMeltingPoint()
{
return meltingPoint;
}
/**
* #return the density
*/
public double getDensity()
{
return density;
}
/**
* #return the molecularWeight
*/
public double getMolecularWeight()
{
return molecularWeight;
}
/**
* #return the count
*/
public int getCount()
{
return count;
}
}
PeriodicTable class: holds methods that will fulfill the menu items
public class PeriodicTable
{
private final static int ARRAY_SIZE= 120;
private Element[] elements;
private int count=110;
Scanner keyboard= new Scanner(System.in);
public PeriodicTable(){
elements = new Element[ARRAY_SIZE];
}
public void readPeriodicTableInfo(Element element){
for(int i=0; i<elements.length;i++){
elements[i]=element;
System.out.println(elements[i].toString());
}
}
public void displayMenu(){
System.out.println("1. Display information for all elements in the Periodic Table");
System.out.println("2. Display information for one element");
System.out.println("3. Display particle information for one element");
System.out.println("4. Display the element with the highest boiling point");
System.out.println("5. Display the element with the lowest melting point");
System.out.println("6. Display the molecular mass calculations for elements in file");
System.out.println("7. Quit");
System.out.print("Please enter your choice: ");
}
public int findElement(String symbol){
System.out.println("Enter element symbol: ");
String elementSymbol=keyboard.next();
for(int i=0; i<elements.length;i++){
if(elementSymbol.equalsIgnoreCase(elements[i].getSymbol())){
return i;
}
}
return -1;
}
public void displayElement(String symbol){
System.out.println();
System.out.println(elements[findElement(symbol)].toString());
}
}
You've got lots of issues in that code, not the least of which your PeriodicTable looks like it will hold multiple references to one and only one Element.
but as to your problem:
Your findElement method should have no println statements,
it should have no keyboard.next() or keyboard statements at all.
it should simply use the String that was passed in via its parameter and search the elements array for the matching element.
You'll also have to fix how it fills up the array so that each array item holds a unique element.
So findElement should be much simpler, something like:
public int findElement(String symbol){
for(int i=0; i<elements.length;i++) {
if(symbol.equalsIgnoreCase(elements[i].getSymbol())){
return i;
}
}
// I'd throw an exception here if no element is found
}
Even better would be to have the method return the found Element object and not the int array index.
Also, a side recommendation: Please look up and try to follow Java code formatting rules. By following these rules, others will more easily be able to read and understand your code, and then be able to help you. If you are using most IDE's they can help you format your code correctly for you.
Edit: This appears to be the most broken method of all:
public void readPeriodicTableInfo(Element element){
for (int i=0; i<elements.length;i++) {
elements[i]=element;
System.out.println(elements[i].toString());
}
}
Let's look at what it does: it loops through the entire elements array, placing the element that is passed into this method into every item within the array, something that I really don't think you want to have happen. Instead, you should add the element passed in to one and only one item in the array. This would be best performed by changing elements from an array to an ArrayList<Element>, and then you could simply call the ArrayList add method. If you can't use that, then you're going to have to use an index variable to keep track of how many elements have already been added, and then add the latest one into the next empty array slot.

Sequential search does not work as expected

I have written a program which takes the words the user have entered, with a button press, and puts them in an ArrayList. There is also another text field where the user can enter a letter or word, for which the user can search for in the ArrayList with another button press. I'm using a sequential search algorithm to accomplish this, but it does not work as I expect it to; If the searched word is found, the search function should return, and print out in a textArea that the word was found and where in the array it was found. This works, but only for the first search. If the word is not found, the function should print out that the word was not found. This works as I want it to.
The problem is that after I searched for one word, and it displays where in the ArrayList this can be found, nothing happens when I press the button after that, whether the entered letter/word is in the array or not. It's like the string that the text gets stored isn't changing. I don't understand why... Here below is the custom Class of the search function and then my Main class:
public class Search {
static private int i;
static String index;
static boolean found = false;
public static String sequencial (ArrayList<String> list, String user) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i).equals(user)) {
index = "The word " + user + " exist on the place " + i + " in the Arraylist";
found = true;
}
}
if (!found) {
index = "The word " + user + " could not be found";
}
return index;
}
My Main class:
ArrayList<String> list = new ArrayList<String>();
ArrayList<String> s = new ArrayList<String>();
private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
txtaOutput.setText("");
String word = txtfAdd.getText();
list.add(word);
for (int i = 0; i < list.size(); i++) {
txtaOutput.append("" + list.get(i) + "\n");
}
}
private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String user = txtfSearch.getText();
txtaOutput.setText("");
String index = Search.sequencial(list, user);
txtaOutput.setText("" + index);
}
Any help is appreciated!
The problem is that you declared your found variable as static. When your first word is found, it is set to true, and nothing ever sets it back to false. Instead of making it a static variable, declare it as a local variable inside your sequencial (it's spelled sequential, by the way) function, just before the for-loop.
In fact, all the variables you've declared as static should be made local. Declaring static variables is never a good idea.
As said by other users:
There is the List#indexOf(Object) method. You should use that instead of reinventing the wheel (unless you need to, and in that case you might have a look at the ArrayList implementation). There are also other collections, like HashSet which are more apropiate for looking up, but i guess that is another history.
The scope and the names of the variables (i, index, found) is error-prone. Do other methods or even classes need to have access to those variables? If you need to keep those variables, you might want to choose a visibility (public,protected,private). "index" is a misleading choice of a name for a message.
This would be an slightly simplified/corrected version of your code:
// Ommit those unneeded static variables
public static String sequencial (ArrayList<String> list, String user) {
int indexFound = list.indexOf(user);
if (user >= 0) {
return "The word " + user + " exist on the place " + indexFound + " in the Arraylist";
} else {
return "The word " + user + " could not be found";
}
}
...
private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {
String user = txtfSearch.getText();
// txtaOutput.setText("");
String seqMessage = sequencial(list, user);
txtaOutput.setText(seqMessage);
}
We use the static properties when you would like to use the constants. You should not use the static properties here. The problem will happen when your found property is changed the first time, it will not be changed again. And from that time, it will always be true. Similar with index property. Here is the code you can fix this:
public class Search {
public static SearchResult sequencial (ArrayList<String> list, String user) {
SearchResult result = null;
for (int i = 0; i < list.size(); i++) {
if (list.get(i).equals(user)) {
String index = "The word " + user + " exist on the place " + i + " in the Arraylist";
boolean found = true;
result = new SearchResult(index, found);
break;
}
}
if (result == null) {
String index = "The word " + user + " could not be found";
result = new SearchResult(index);
}
return result;
}
//sample inner class
static class SearchResult {
private String index;
private boolean found;
public SearchResult(String index) {
this.index = index;
}
public SearchResult(String index, boolean found) {
this.index = index;
this.found = found;
}
public String getIndex() {
return index;
}
public void setIndex(String index) {
this.index = index;
}
public boolean isFound() {
return found;
}
public void setFound(boolean found) {
this.found = found;
}
}
}
public class SequencialSearcher {
public static int SequencialSearchInt(int[] inputArray, int key)
{
for(int i=0; i < inputArray.length ; i++)
{
if(inputArray[i] == key)
{
return i;
}
}
return -1;
}
public static int SequencialSearchString(String[] array, String key)
{
for(int i=0; i < array.length ; i++)
{
if(array[i] == key)
{
return i;
}
}
return -1;
}
public static int SequencialSearchFloat(double[] array, double key)
{
for(int i=0; i < array.length ; i++)
{
if(array[i] == key)
{
return i;
}
}
return -1;
}
public static void main (String args[])
{
//select the type of the elements of search
//1 if integers
//2 if float
//3 if string
int x = 3;
int[] array1 = {9, 0, 10, 8, 5, 4, 6, 2, 3};
double[] array2 = {9.0, 0.0, 10.0, 8.0, 5.0, 4.0, 6.0, 2.0, 3.0};
String[] array3 = {"aa","hey", "hello"};
if(x == 1){
//enter the integer you want to search for here below
int requiredValue = 5;
int result = SequencialSearchInt(array1, requiredValue);
if (result != -1)
{
System.out.println("Required Value: "+requiredValue+" found at index: "+result);
}
else
{
System.out.println("Value:"+requiredValue+" not found");
}
}
else if(x == 2)
{
//enter the double you want to search for here below
double requiredValue1 = 5.0;
int result = SequencialSearchFloat(array2, requiredValue1);
if (result != -1)
{
System.out.println("Required Value: "+requiredValue1+" found at index: "+result);
}
else
{
System.out.println("Value:"+requiredValue1+" not found");
}
}
else if(x == 3){
//enter the string you want to search for here below
String requiredValue2 = "hey";
int result = SequencialSearchString(array3, requiredValue2);
if (result != -1)
{
System.out.println("Required Value: "+requiredValue2+" found at index: "+result);
}
else
{
System.out.println("Value:"+requiredValue2+" not found");
}
}
else{
System.out.println("Error. Please select 1,2 and 3 only");
}
}
}

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

Sorting a integer list without a sort command

So I have this code:
public class SortedIntList extends IntList
{
private int[] newlist;
public SortedIntList(int size)
{
super(size);
newlist = new int[size];
}
public void add(int value)
{
for(int i = 0; i < list.length; i++)
{
int count = 0,
current = list[i];
if(current < value)
{
newlist[count] = current;
count++;
}
else
{
newlist[count] = value;
count++;
}
}
}
}
Yet, when I run the test, nothing prints out. I have the system.out.print in another class in the same source.
Where am I going wrong?
EDIT: Print code from comment:
public class ListTest
{
public static void main(String[] args)
{
SortedIntList myList = new SortedIntList(10);
myList.add(100);
myList.add(50);
myList.add(200);
myList.add(25);
System.out.println(myList);
}
}
EDIT2: Superclass from comment below
public class IntList
{
protected int[] list;
protected int numElements = 0;
public IntList(int size)
{
list = new int[size];
}
public void add(int value)
{
if (numElements == list.length)
System.out.println("Can't add, list is full");
else {
list[numElements] = value; numElements++;
}
}
public String toString()
{
String returnString = "";
for (int i=0; i<numElements; i++)
returnString += i + ": " + list[i] + "\n";
return returnString;
}
}
Let's walk through the logic of how you want it to work here:
first you make a new sorted list passing 10 to the constructor, which make an integer array of size 10.
now you call your add method passing 100 into it. the method sets position 0 to 100
now you add 50, the method sets 50 in position 0 and 100 in position 1
now you add 200, which gets placed at position 2
and you add 25. which gets set to position 0, and everything else gets shuffled on down
then your method will print out everything in this list.
So here are your problems:
For the first add, you compare current, which is initialized at 0, to 50. 0 will always be less than 50, so 50 never gets set into the array. This is true for all elements.
EDIT: Seeing the super class this is how you should look to fix your code:
public class SortedIntList extends IntList
{
private int[] newlist;
private int listSize;
public SortedIntList(int size)
{
super(size);
// I removed the newList bit becuase the superclass has a list we are using
listSize = 0; // this keeps track of the number of elements in the list
}
public void add(int value)
{
int placeholder;
if (listSize == 0)
{
list[0] = value; // sets first element eqal to the value
listSize++; // incriments the size, since we added a value
return; // breaks out of the method
}
for(int i = 0; i < listSize; i++)
{
if (list[i] > value) // checks if the current place is greater than value
{
placeholder = list[i]; // these three lines swap the value with the value in the array, and then sets up a comparison to continue
list[i] = value;
value = placeholder;
}
}
list[i] = value; // we are done checking the existing array, so the remaining value gets added to the end
listSize++; // we added an element so this needs to increase;
}
public String toString()
{
String returnString = "";
for (int i=0; i<listSize; i++)
returnString += i + ": " + list[i] + "\n";
return returnString;
}
}
Now that I see the superclass, the reason why it never prints anything is clear. numElements is always zero. You never increment it because you never call the superclass version of the add method.
This means that the loop in the toString method is not iterated at all, and toString always just returns empty string.
Note
This is superseded by my later answer. I have left it here, rather than deleting it, in case the information in it is useful to you.
Two problems.
(1) You define list in the superclass, and presumably that's what you print out; but you add elements to newList, which is a different field.
(2) You only add as many elements to your new list as there are in your old list. So you'll always have one element too few. In particular, when you first try to add an element, your list has zero elements both before and after the add.
You should probably have just a single list, not two of them. Also, you should break that for loop into two separate loops - one loop to add the elements before the value that you're inserting, and a second loop to add the elements after it.

Categories

Resources