Setting an array of objects and searching through it for variables - java

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.

Related

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

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

How do I refactor an array field into an ArrayList

This is a program that allows users to add data to a system. This is specifically the invetory class of the program where our task is to convert the object inventory into an object of an array list... I am new to array lists and I would like some assistance figuring this out.
I have tried a few times but have had no luck so far, anything helps!
public class Inventory {
/**
* List of FoodItems that represents our inventory
*/
private FoodItem[] inventory;
/**
* Number of items that a user has entered
*/
private int numItems;
/**
* Default Constructor
*/
public Inventory() {
inventory = new FoodItem[20];
}
/**
* Reads from the Scanner object passed in and fills the data member fields of the class with valid data.
* #param scanner - Scanner to use for input
* #return <code>true</code> if all data members were successfully populated, <code>false</code> otherwise
*/
public boolean addItem(Scanner scanner) {
if(numItems == 20)
{
System.out.println("Inventory full");
return false;
}
boolean valid = false;
FoodItem item = null;
while(!valid)
{
System.out.print("Do you wish to add a fruit(f), vegetable(v) or a preserve(p)? ");
if(scanner.hasNext(Pattern.compile("[fFvVpP]")))
{
String choice = scanner.next();
switch(choice.toLowerCase())
{
case "f":
item = new Fruit();
break;
case "v":
item = new Vegetable();
break;
case "p":
item = new Preserve();
break;
default: // Should not get here.
item = new FoodItem();
break;
}
valid = true;
}
else
{
System.out.println("Invalid entry");
scanner.next();
valid = false;
}
}
if(item.inputCode(scanner))
{
if(alreadyExists(item)<0)
{
if(item.addItem(scanner))
{
inventory[numItems] = item;
numItems++;
return true;
}
return false;
}
else
{
System.out.println("Item code already exists");
return false;
}
}
return true;
}
/**
* Search for a food item and see if it is already stored in the inventory
* #param item - FoodItem to look for
* #return - The index of item if it is found, -1 otherwise
*/
public int alreadyExists(FoodItem item) {
for(int i=0;i<numItems;i++)
{
if(inventory[i].isEqual(item))
return i;
}
return -1;
}
/**
* Update the quanity stored in the food item
* #param scanner - Input device to use
* #param buyOrSell - If we are to add to quantity (<code>true</code>) or remove (<code>false</code>)
* #return
*/
public boolean updateQuantity(Scanner scanner, boolean buyOrSell) {
// If there are no items then we can't update, return
if(numItems == 0)
return false;
FoodItem temp = new FoodItem();
temp.inputCode(scanner);
int index = alreadyExists(temp);
if(index != -1)
{
String buySell = buyOrSell?"buy":"sell";
System.out.print("Enter valid quantity to "+buySell+": ");
if(scanner.hasNextInt())
{
int amount = scanner.nextInt();
if(amount > 0)
{
return inventory[index].updateItem(buyOrSell? amount: amount*-1);
}
else
{
System.out.println("Invalid quantity...");
}
}
else
{
System.out.println("Invalid quantity...");
}
}
return false;
}
#Override
public String toString() {
String returnString = "Inventory:\n";
for(int i=0;i<numItems;i++)
returnString += inventory[i].toString() + "\n";
return returnString;
}
}
I could be misunderstanding the question, but I'm guessing you want to convert Inventory to use an ArrayList, rather than convert it into an ArrayList. Is that correct?
If I understood the question correctly, then the first thing you'll want to do is change the declaration of the inventory field to an ArrayList:
private List<FoodItem> inventory;
Notice that I've declared this as the List interface, rather than the concrete ArrayList implementation. Unless there's a specific feature of the ArrayList implementation you need that's not available in the generic interface, it's usually best to operate at the generic interface level to give yourself the most flexibility.
However, in the constructor, you'll actually instantiate the concrete ArrayList:
public Inventory() {
inventory = new ArrayList<>(20);
}
By switching from a bare array to an ArrayList, you'll find the first advantage of using a Collection, in that you won't need the alreadyExists() method any longer. List, and its super interface, Collection, supports the contains() method.
This:
if(alreadyExists(item)<0)
becomes:
if (!inventory.contains(item))
...and you can remove the alreadyExists() method.
The second advantage is that you'll no longer need to track the number of items in the inventory as a separate field. List already provides this for you.
This:
if(numItems == 20)
becomes:
if (inventory.size() == 20)
..and you can delete the numItems field from your class.
The third advantage is that List/Collection supports a toString() very similar to the implementation you have above.
This:
#Override
public String toString() {
String returnString = "Inventory:\n";
for(int i=0;i<numItems;i++)
returnString += inventory[i].toString() + "\n";
return returnString;
}
becomes:
#Override
public String toString() {
return "Inventory:\n" + inventory.toString();
}
The main difference between your toString() and the toString() provided by List is that you have new lines between each item, and List simply puts commas between each item. If you wanted to keep the new lines, then the looping on List/Collection is a little less cumbersome than arrays:
#Override
public String toString() {
String returnString = "Inventory:\n";
for(FoodItem item : inventory) {
returnString += item.toString() + "\n";
}
return returnString;
}

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
}

Handling a Circular Queue that is Made Up of Objects

I am trying to create a circular queue that will hold objects. The idea is the user will either buy or sell stock, and each time a stock is purchased, that object will hold the amount of stock purchased and the price is was purchased for in the queue. This queue is an array based queue with a size of 32 and every time the user selects to buy, it will fill another slot.
If the user elects to sell stock, the number of stocks sold will be subtracted from the first object unless the user sells more stock than the first slot contains, in that case it will subtract from the subsequent slot. Once the slot has had all of it's stock sold...aka it has no more shares, that object can be dequeued and it will free up a slot to buy stock once the queue comes around to that position
I am struggling on handling the object types. Especially when I try to dequeue just for testing to see if I can dequeue properly.... I will get the last slot when I dequeue even though I am pretty sure the method is right, I am just having difficulty handling the classes/objects.
NOTE: I must manually create the array/queue, so I can't use the Java built in array
StockTran class.......Has Stock as a nested class
import java.util.Scanner;
//Once you reach the end of the array, you are going to get an out of bounds exception if you try to enqueue again
//So if there are any open boxes on the very front of the array, say a[0] is empty, you can place the extra array spot at a[0]
//Then keep going
//You can handle the overflow and make the array circular or at least get the size by using (get + put)%size...So if (4+5)%8
//the answer is 1... meaning the size is 1.
//Create a total variable thats adds up the total of shares each spot in the array has...This way you can say you don't have
//that many shares if they try to sell more than what you actually have....Also look at the amount of shares each spot has
//and only dequeue when the total of shares for that spot is used up..."Only dequeue a truck when it's empty"
//User is prompted to enter in either b, s, c, or q.....
//b = buy shares, s = sell shares, c = capital gain from buying and selling q = quit the program
//Must be formatted by letter (space) number (space) number........ EX: b 10 10 .... this will buy 10 shares at $10 each
//This is the class I am storing in the queue.....Can call methods on it to get out crucial data
class Stock {
public int getShares() {
return shares;
}
public void setShares(int shares) {
this.shares = shares;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
private int shares;
private int price;
// Get price Get Shares set price get set price
public void stockTran() {
// total gain,
}
}
//Class that handles the user's input, should handle the math for profit, subtracting, etc....Basically the class that
//links all the other classes/methods together
public class StockTran {
// Declaring variables
private MyQueue<Stock> queueArray; // Size of Array/Queue is 32
static String firstCommand; // The first token of the scanner...Looks
// whether b,s, or c
static int shares; // How many shares that are bought/sold
static int price; // The price those shares are bought/sold at
static int netProfit = 0; // Initializing the profit so it can be
// added/subtracted later
static int put, get = 0; // Declaring the front and rear portions of the queue
static int total = 0; // Initial number of elements in the array, this will
// increase/decr
public static void main(String[] args) {
StockTran eg = new StockTran();
eg.queueArray = new MyQueue<Stock>(32);
Stock test = new Stock();
// Prompts the user to enter an input
// The if/else if ladder is used to call the correct methods based on
// the user input..Reads by looking
// at the tokens
while (true) {
Scanner reader = new Scanner(System.in);
System.out.println("Enter the proper formatted commands ");
firstCommand = reader.next();
if (firstCommand.equalsIgnoreCase("b")) {
shares = reader.nextInt();
price = reader.nextInt();
test.setPrice(price);
test.setShares(shares);
eg.queueArray.enqueue(test);
System.out.println("Price: " + test.getPrice());
System.out.println("Shares: " + test.getShares());
System.out.println("Size: " + eg.queueArray.size());
// System.out.println("Buying " + shares + " shares" + ", " +
// "$" + price + " each");
} else if (firstCommand.equalsIgnoreCase("s")) {
System.out.println("dequeued price: " + ((Stock) eg.queueArray.dequeue()).getPrice());
System.out.println("dequeued shares: " + ((Stock) eg.queueArray.dequeue()).getShares());
System.out.println("Size: " + eg.queueArray.size());
}
else if (firstCommand.equalsIgnoreCase("c")) {
System.out.println("Capital gain");
} else if (firstCommand.equalsIgnoreCase("q")) {
System.out.println("Quitting");
break;
} else {
System.out.println("Command Not Recognized!");
}
}
}
// This method will either add or subtract from the total profit depending
// upon the buying and selling....Not finished yet
public int calculate(int netProfit) {
int i = 0;
while (i < shares) {
i++;
}
return netProfit;
}
}
Queue Interface
public interface Queue <E> {
//Gets the size of array queue
public int size();
//Checks if the queue is empty
public boolean isEmpty();
//Looks at the first item
public Object front() throws EmptyQueueException;
//Puts an element at the end of the array
// public void enqueue (Node element);
public void enqueue (E element);
//Removes an element from the front of the array
public Object dequeue() throws EmptyQueueException;
}
MyQueue class
// Creates the node and allows methods to assign, get the next element, and set elements
// for the node
//So you create a node class with quanitity and price.... Has to be an object
public class MyQueue <E> implements Queue <E>
{
//Instance variables
private Object [] queue;
private int front, rear = 0; //Pointers for the queue....Locates where the next enqueue/dequeue spot should be
private int max = 32; //Size of my queue
private int size;
public MyQueue(int max)
{
this.queue = new Object[max];
}
#Override
public int size() {
// TODO Auto-generated method stub
size = (rear - front)%32;
return (rear - front)%32;
}
#Override
public boolean isEmpty() {
// TODO Auto-generated method stub
if (front == rear)
return true;
else
return false;
}
//Gets the front object of the queue
#Override
public Object front() throws EmptyQueueException {
// TODO Auto-generated method stub
return queue[front];
}
//Adds an element to the end of the queue
#Override
public void enqueue(E element) {
// TODO Auto-generated method stub
this.queue[this.rear%this.max] = element;
if (rear < 32)
rear++;
else
rear = 0;
System.out.println("Font is: " + front);
System.out.println("Rear is: " + rear);
}
//Removes an element from the front of the queue
#Override
public Object dequeue() throws EmptyQueueException {
Object temp = null;
if (isEmpty() == true){
throw new EmptyQueueException("Empty Queue!");
}
if(size() > 0 && front != size){
temp = queue[front];
System.out.println(": " + temp);
front = front + 1;
}
else if(front == size())
front = 0;
System.out.println("Font is: " + front);
System.out.println("Rear is: " + rear);
return temp;
}
}
Thank you!

Arrays with mutliple elements in java and other Issue

Having problems linking this program to this class. The program takes in a set of String + double arrays and goes through a series of sorts to yield a result. Our instructions are to sort then by name and sort then by price.
Main problem is that the Strings are displaying as hexadecimal eg(Item#4fjipe) etc.
Second problem is my sorts. I just have no idea how to make them work. Please help if at all possible. I will include both the class and the program. Bear in mind they are 2 different .java working together. I'm a beginner, by the way.
public class Item
{
private String itemName; // hold the name of the item
private double itemPrice; // hold the price of the item
public Item(String s, double p) // Constructor
{
itemName = s;
itemPrice = p;
}//end constructor
public void setName(String n)
{//method to set the item name
itemName = n;
}//end method
public String getName()
{//method to get the item name
return itemName;
}//end method
public double setPrice(double p1)
{//method to set the price of the item
itemPrice = p1;
return itemPrice;
}//end method
public double getPrice()
{//method to get the price of the item
return itemPrice;
}//end method
}//end class
AND NOW THE OTHER BEGINS. THIS ONE IS STILL A HOT MESS.
import javax.swing.*;
import java.util.Arrays;
public class CoffeeDriver
{
public static void main (String[] args)
{
Item[] itemArray = new Item[5]; // Array of type Item declaration
boolean loopControl = false; //variable for control of our loop
while (!loopControl)
{
itemArray[0] = new Item("Coffee", 1.00);
itemArray[1] = new Item("Water", 2.00);
itemArray[2] = new Item("Milk", 1.50);
itemArray[3] = new Item("Bagel",1.25);
itemArray[4] = new Item("Donut", 0.75);
String input = JOptionPane.showInputDialog(null, "Welcome to Wings Coffee Shop. We have a great list items on our menu. \nWould you like to see these items sorted by name of by price? (n/p):");
if(input.equals("n"))
{
sortName(itemArray);
JOptionPane.showMessageDialog(null, itemArray);
}//end if
else if(input.equals("p"))
{
sortPrice(itemArray);
JOptionPane.showMessageDialog(null, itemArray);
}
else
{
loopControl = true;
}
}//end while
}//end main
public static void sortName(Item[] itemArray)
{
int n = itemArray.length;
Item temp = new Item("",0);
for (int i =0; i < n; i++)
{
for(int j =1; j<(n-1); j++)
{
temp.setPrice(itemArray[j+1].getPrice());
temp.setName(itemArray[j+1].getName());
if(itemArray[j+1] == itemArray[j])
{
temp.setPrice(itemArray[j+1].getPrice());
temp.setName(itemArray[j+1].getName());
itemArray[j+1].setPrice(itemArray[j].getPrice());
itemArray[j+1].setName(itemArray[j].getName());
itemArray[j].setPrice(temp.getPrice());
itemArray[j].setName(temp.getName());
temp = itemArray[j+1];
itemArray[j+1] = itemArray[j];
itemArray[j] = temp;
JOptionPane.showMessageDialog(null, itemArray);
}//end if
}//end inner for
}//end outer for
}//end sortName
public static void sortPrice(Item[] itemArray)
{
int n = itemArray.length;
Item temp = new Item("",0);
for (int i =0; i < n; i++)
{
for(int j =1; j<(n-1); j++)
{
temp.setPrice(itemArray[j+1].getPrice());
temp.setName(itemArray[j+1].getName());
if(itemArray[j+1] == itemArray[j])
{
temp.setPrice(itemArray[j+1].getPrice());
temp.setName(itemArray[j+1].getName());
itemArray[j+1].setPrice(itemArray[j].getPrice());
itemArray[j+1].setName(itemArray[j].getName());
itemArray[j].setPrice(temp.getPrice());
itemArray[j].setName(temp.getName());
temp = itemArray[j+1];
itemArray[j+1] = itemArray[j];
itemArray[j] = temp;
JOptionPane.showMessageDialog(null, itemArray);
}//end if
}//end inner for
}//end outer for
}//end sortPrice
}//end class
You need to override the toString method in your Item class. You could use:
#Override
public String toString() {
return "Item [itemName=" + itemName + ", itemPrice=" + itemPrice + "]";
}
As you need to have 2 separate methods to sort by name and by price, you could use a custom comparator for both cases, using the appropriate field to compare against. Have a look at Arrays.sort() for doing the actual sorting.
'Item#4fjipe' is the object reference as provided by the default implementation of Object.toString() - read the API for reference.
A hexadecmial literal in Java start swith 0x, e.g. 0x10.
For your specific problem, you have a data object that you wish to sort in 2 different ways. Read the API documentation for Comparator and Comparable. Then check the Collections API to see which collections might offer you sorting.

Categories

Resources