Handling a Circular Queue that is Made Up of Objects - java

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!

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

Why won't my recursive function recurse through all of the data in the stack?

I am trying to reverse a stack of type int using recursion. I am able to reverse the first entry, but it shows only zeros when I try to print the supposed reversed stack after the recursion takes place. Here is my code:
//Class to reverse a stack using recursion
class ReverseStack
{
//Global Variables
static int[] stack = new int[5];
static int[] tempStack = new int[5];
private static int size;
//Constructor
public ReverseStack()
{
}
//Functions to for the stack
public static boolean isEmpty()
{
return size == 0;
}
//Function to determine if stack is full
public static boolean isFull()
{
return size == stack.length;
}
//Function to determine size of array
int size()
{
return size;
}
//Function to push entries into stack
public static boolean push(int[] stack, int data)
{
if(isFull())
{
return false;
}
else
{
stack[size] = data;
size++;
return true;
}
}
//Function to remove entries from stack
public static int pop()
{
if(isEmpty())
{
return 0;
}
else
{
size--;
return(stack[size + 1]);
}
}
//Function to print the stack
public static void print(int[] stack)
{
//This prints top to bottom
//Top is the last entry
System.out.println("Top to Bottom");
if(isEmpty())
{
System.out.println("The stack is empty ");
}
else
{
for(int cntr = 0; cntr < size; cntr++)
{
System.out.println(stack[cntr] + " ");
}
}
}
//Function to reverse data recursively
public static void reverseData(int data)
{
//Variables
int tempNum;
int cntr = 4;
int cntr2 = 0;
//Note:
/*
To reverse a stack we need to
1. pass in a number
2. Remove the number
3. Repeat until no numbers are left
4 copy stack
5. print
*/
if(data > stack[cntr - 1])
{
tempStack[cntr2] = data;
cntr--;
cntr2++;
data = stack[cntr - 1];
reverseData(data);
}
}
}
I call this reverseStack function in my program's menu system:
//Function to create a menu system
public static void menu()
{
//Variables
int response;
//Message user
System.out.println("Would you like to: "
+ "\n(1) Reverse a stack using recursion "
+ "\n(2) Draw the Sierpinski Triangle "
+ "\n(3) Draw the Dragon Curve "
+ "\n(4) Recurse through a file/directory system"
+ "\n(5) Recurse through my own recursive function"
+ "\n(6) Quit the program ");
//Save user's response
response = Integer.parseInt(myScanner.nextLine());
//Switch statement for menu options
switch (response)
{
case 1:
{
//Create a new instance of ReverseStack class
ReverseStack rs = new ReverseStack();
//Add data into stack before reversing the stack
rs.push(stack, 10);
rs.push(stack, 20);
rs.push(stack, 30);
rs.push(stack, 40);
rs.push(stack, 50);
//Print stack
rs.print(stack);
//Call function to reverse data set
rs.reverseData(stack[4]);
//Print data set
rs.print(rs.tempStack);
//Return to menu
menu();
break;
}
}
}
Do you know what I may be doing wrong?
Size seems to be always 1 above the index of the last element in the stack, so your pop method should probably be
size--;
return stack[size]; // not stack[size+1]
Also your reverseData function is not working because you are resetting cntr and cntr2 each time the function is called. Those must be global variables.
Maybe try something like
int counter = 0;
public void reverseData (int index) {
if (index > counter) {
int temp = data[index];
data[index] = data[counter];
data[counter] = temp;
counter++;
reverseData(--index);
}
You need to know the next index of your tempStack. Right now it is always 0. So you are only updating the first value and rest are 0s
Change your method
//Function to reverse data recursively
public static void reverseData(int data)
{
//Variables
int tempNum;
int cntr = 4;
int cntr2 = 0;
//Note:
/*
To reverse a stack we need to
1. pass in a number
2. Remove the number
3. Repeat until no numbers are left
4 copy stack
5. print
*/
if(data > stack[cntr - 1])
{
tempStack[cntr2] = data;
cntr--;
cntr2++;
data = stack[cntr - 1];
reverseData(data);
}
}
with this
//Function to reverse data recursively
public static void reverseData(int data, int cntr2)
{
//Variables
int tempNum;
int cntr = 4;
//Note:
/*
To reverse a stack we need to
1. pass in a number
2. Remove the number
3. Repeat until no numbers are left
4 copy stack
5. print
*/
if(data > stack[cntr - 1])
{
tempStack[cntr2] = data;
cntr--;
cntr2++;
data = stack[cntr - 1];
reverseData(data, cntr);
}
}
In your main method, call reverseData(stack[4], 0)
Or create cntr2 as class level variable
If it is a temp stack please not define it as static variable. It is not safe and not good coding behavior.
You used two pointers. The cntr points to the last variable, and the cntr2 points to the first variable. Why not compare them?
For example, keep recursing until the cntr2 less than cntr.

How can I calculate the number of moves made between the stacks?

In my current assignment I'm supposed to move elements between three stacks. I have one more method to write: getNumberOfMoves() and it should calculate the number of moves made between the stacks.
I want to add a calculator of some sort but the assignment says that I should write a more specific method for this. Any suggestions for how one can calculate the number of moves using a method?
Also, I'm having trouble with the method move(). I'm supposed to use push() and pop() from the other class. I did some just too see what happens, see code below, but I think I'm supposed to do it with recursion. So the base cases then should be that if the first stack 'from' only contains one element, then this should be moved directly to 'to', otherwise the last element should be moved to the 'help' stack and then to 'to'.
But, the question is, if I'm doing it recursively, shouldn't I be calling the method within the method? Then how am I supposed to use pop() and push()?
Thanks in advice!
public class StackPlay {
/**
* Returns the current number of times an element has been moved
* #return the number of moves
*/
public static long getNumberOfMoves() {
}
public static void move(myStack from,
myStack to,
myStack help,
int n) {
help.push(from.pop());
to.push(help.pop());
}
public static void main(String[] args) {
int size = 3;
myStack from = new myStack(size);
myStack to = new myStack();
myStack help = new myStack();
System.out.println("Start state");
System.out.println(" From: " + from);
System.out.println(" To: " + to);
System.out.println(" Help: " + help);
System.out.println(" Number of moves: " + getNumberOfMoves());
move(from, to, help, size);
System.out.println("End state");
System.out.println(" From: " + from);
System.out.println(" To: " + to);
System.out.println(" Help: " + help);
System.out.println(" Number of moves: " + getNumberOfMoves());
}
}
and separate class:
public class myStack {
private ArrayList<Integer> specStack;
public myStack() {
specStack = new ArrayList<Integer>();
}
public myStack(int n) {
this.specStack = new ArrayList<Integer>(n);
int i;
for (i=0; i<n; i++) {
specStack.add(i, n-i);
}
}
public void push(int x) {
if (specStack.size() == 0) {
specStack.add(x);
}
else if (x > specStack.get(specStack.size() -1)) {
throw new RuntimeException("Number too high");
}
else {
specStack.add(x);
}
}
public int pop() {
if (specStack.size() == 0) {
throw new RuntimeException("Empty stack");
}
else {
int length = specStack.size() -1;
int topEl = specStack.get(length);
specStack.remove(length);
return topEl;
}
}
public String toString() {
String arrList = "[";
int i;
for (i = 0; i < specStack.size(); i++) {
if (i == specStack.size() -1) {
arrList = arrList + specStack.get(i);
}
else {
arrList = arrList + specStack.get(i) + ",";}
}
arrList = arrList + "]";
return arrList;
}
}

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.

Categories

Resources