My program stops after the first element gets into array. Could you help me? Here's the code:
sorry for that
i've made some changes now ArrayQueue is my class where all my methods are implemented
QueueElement is another class that holds the type of element..
i think the problem now is at the ArrayQueue class
import java.io.*;
import java.util.Scanner;
public class QueueTest
{ private static Scanner scan =new Scanner(System.in);
public static void main(String[] args)
{
ArrayQueue queue = new ArrayQueue();
System.out.println("insert :" +
" P: to print the array "+
"S: to sort "+
"E: to empty");
do
{
if (userInput.startsWith("Y")) {
System.out.println("insert the value of element");
int vl = scan.nextInt();
System.out.println("insert the description");
String p = scan.next();
System.out.println("insert true or false");
boolean vlf = scan.nextBoolean();
queue.shtoElement(new QueueElement(vl, p, vlf));
} else if (userInput.startsWith("P")) {
queue.shfaqArray();//display the array
} else if (userInput.startsWith("S")) {
queue.rendit();//sort the array
} else if (userInput.startsWith("E")) {
queue.Empty();//empty array
}
System.out.println("Insert:" + " P: to display the array "
+ " S: to sort array "
+ " E: to empty");
userInput = scan.next();
} while (!userInput.equalsIgnoreCase("exit"));
}
}
here is the class ArrayQueue
public class ArrayQueue implements Queue
{
//build the queue
QueueElement[] tabela= new QueueElement[MADHESIA];
QueueElement element= new QueueElement();
//test if queue is empty
public boolean isEmpty()
{
boolean empty = true;
for(int k =0;k<tabela.length;k++)
{
if(tabela[k] !=null)
empty =false;
break;
}
return empty;
}
public boolean isFull()
{
boolean full=false;
for(int k=0;k<tabela.length;k++)
{
if(tabela[k]!=null)
full=true;
break;
}
return full;
}
//sort the array
public void rendit()
{
QueueElement temp=tabela[0];
for(int i=0;i<tabela.length;i++)
{
for(int j=i+1;j<tabela.length;j++)
if(tabela[j]!=null)
{
if(tabela[j].compareTo(tabela[i])==1)
{
tabela[j]=temp;
tabela[i]=tabela[j];
temp=tabela[i];
}
else
{
nrElementeve++;
}
}
if(tabela[i].getVlefshmeria()==false)
{
hiqElement(i,temp);
}
}
}
// add element into the array
public void shtoElement(QueueElement el)
{
if(isEmpty())
{
tabela[0]=el;
}
else
{
for(int i=0;i<tabela.length;i++)
{
if(tabela[i]!= null && (el.compareTo(tabela[i])==0))
{
System.out.println("element can't be added into array cause it exists !");
}
{
if(isFull())
{
int index=tabela.length;
tabela=rritMadhesine(tabela);
tabela[index]=el;
}
else
{
for(int j=0;j<tabela.length;j++)
{
if(tabela[j]==null)
tabela[j]=el;
break;
}
}
}
}
}
}
//find max of array
public QueueElement gjejMax()
{
QueueElement max = tabela[0];
for (QueueElement element :tabela)
{
if(element.getValue() > max.getValue())
{
max =element;
}
return max;
}
return max;
}
//find min of array
public QueueElement gjejMin()
{
QueueElement min= tabela[0];
for(QueueElement element : tabela)
{
if(element.getValue()< min.getValue())
{
min=element;
}
return min;
}
return min;
}
//remove element from array
public void hiqElement(int indeksi, QueueElement temp)
{
if(tabela.length > 0)
{
if(gjejMax().compareTo(temp)==0 || gjejMin().compareTo(temp)==0)
{
System.out.println("element can't be removed!");
}
else
{
for(int i=indeksi;i<tabela.length;i++)
{
tabela[i]=tabela[i+1];
}
}
nrElementeve--;
}
}
//empty array
public void Empty()
{
tabela= new QueueElement[MADHESIA];
}
//display the array
public void shfaqArray()
{
for(int i=0;i< tabela.length;i++)
{
if(tabela[i]!=null)
{
System.out.println(tabela[i]);
}
else
break;
}
}
//increase the length of array
public static QueueElement [] rritMadhesine(QueueElement[] array){
QueueElement[] tab=new QueueElement[array.length+2];
return tab;
}
private int nrElementeve;
private static final int MADHESIA = 10;
}
Don't know what ArrayQueue and QueueElement are, but...
It seems like you're reading user input then going through a decision tree to decide what to do based on that input. But at each point, you are re-reading the user input:
if(scan.next().startsWith("Y"))
{
System.out.println("Jepni vleren e elem");
vl=scan.nextInt();
System.out.println("Jepni pershkrimin e elem");
p=scan.next();
System.out.println("Jepni vlefshmerine e elem");
vlf=scan.nextBoolean();
queue.shtoElement(new QueueElement(vl,p,vlf));
}
else
{
if(scan.next().startsWith("P"))
queue.shfaqArray();
}
if(scan.next().startsWith("E"))
queue.Empty();
if(scan.next().startsWith("S"))
queue.rendit();
else
{
break;
}
I think you want something more like:
String userInput = scan.next();
if(userInput.startsWith("Y"))
{
System.out.println("Jepni vleren e elem");
vl=scan.nextInt();
System.out.println("Jepni pershkrimin e elem");
p=scan.next();
System.out.println("Jepni vlefshmerine e elem");
vlf=scan.nextBoolean();
queue.shtoElement(new QueueElement(vl,p,vlf));
}
else if(userInput.startsWith("P"))
queue.shfaqArray();
else if(userInput.startsWith("E"))
queue.Empty();
else if(userInput.startsWith("S"))
queue.rendit();
else
{
break;
}
Where you read the user input once (String userInput = scan.next();) and then decide what to do based on the userInput variable and not re-scan each time. Also, it looks like you might be missing a couple of else statements somewhere in the middle there.
Related
My program has 6 classes so I'm going to try and only post the methods involved with the issue I'm having. I'm trying to add donation objects that get their attributes from reading information from a file. My program wasn't printing out any of the donationList related information so I did a System.out.println(donationList.size()); and it's telling me that there are 0 objects in the list. I've been looking at this for a while and can't figure out where in the process the donation object is failing to be created correctly or added to the arraylist correctly.
This is where I call the method that starts the process.
public static void main(String[] args) {
readAndProcess();
This is the method that starts the process.
public static void readAndProcess() {
final String INPUT_FILENAME = "input/assn2input.txt";
File dataFile = new File(INPUT_FILENAME);
Scanner fileScanner = null;
try {
fileScanner = new Scanner(dataFile);
}catch (FileNotFoundException e) {
System.out.println("File not found exception for file " + e);
System.exit(0);
}
String oneLine;
String [] lineValues;
while(fileScanner.hasNextLine()) {
oneLine = fileScanner.nextLine();
lineValues = oneLine.split(",");
if(lineValues[0].equals("DONOR")) {
if (lineValues[1].equals("ADD") ) {
addDonor(lineValues);
}
else if (lineValues[1].equals("DEL")) {
// call method to delete
}
}
else if ( lineValues[0].equals("Donation")) {
if (lineValues[1].equals("ADD")) {
addDonation(lineValues);
}
else if (lineValues[1].equals("DEL")) {
// call method to delete
}
}
}
}
This is the addDonation method which happens after the readAndProcess method.
public static void addDonation(String [] lineValues) {
Donation donation = new Donation();
setDonationAttributes(donation, lineValues);
if (donorImpl.isIDUnique(donation.getDonorID()) == false &&
donationImpl.isIDUnique(donation.getDonationID()) == true) {
donationImpl.add(donation);
}
else {
System.out.println("ERROR: The Donation either had a non-unique"
+ " donation ID or a unique Donor ID. Was not "
+ "added to list." + donation.toString());
}
}
This is the method that sets the donation object's attributes.
public static Donation setDonationAttributes (Donation donation,
String [] lineValues) {
donation.setDonationID(Integer.parseInt(lineValues[2]));
donation.setDonorID(Integer.parseInt(lineValues[3]));
donation.setDonationDescription(lineValues[4]);
if (donation.checkDescriptionLength() == false) {
System.out.println("ERROR: Donation description is longer "
+ "than 25 characters");
}
donation.setDonationAmount(Double.parseDouble(lineValues[5]));
donation.setDonationDate(lineValues[6]);
if (lineValues[7].equalsIgnoreCase("Y") ) {
donation.setTaxDeductible(true);
}
else {
donation.setTaxDeductible(false);
}
donation.setCheckNumber(Integer.parseInt(lineValues[8]));
if (donation.checkNumberCheck()== false) {
System.out.println("ERROR: Invalid check number is not between 100 "
+ "and 5000: " + lineValues[8]);
}
return donation;
}
This is the method that checks for unique ID for donationID.
public boolean isIDUnique(int donationID) {
int index;
for (index = 0; index < donationList.size(); ++index) {
if (donationID == donationList.get(index).getDonationID() ) {
return false;
}
}
return true;
}
This is the method for checking unique donorID.
public boolean isIDUnique(int donorID) {
int index;
for (index = 0; index < donorList.size(); ++index) {
if (donorID == donorList.get(index).getDonorID() ) {
return false;
}
}
return true;
}
This is the method in the DonationImpl class that adds the object to the arraylist. The instructions for this method told me to set it up as a boolean for whatever reason, I'm not exactly sure why.
public boolean add (Donation donation) {
if (donationList.add(donation)) {
return true;
}
return false;
}
The donationImpl class to show what the arrayList creation looks like.
public class DonationImpl {
// Data Field
private ArrayList<Donation> donationList = new ArrayList<Donation>();
//Getter
public ArrayList<Donation> getDonationList() {return donationList;}
The 1 and 3 in the following examples refer to a donorID. My donorID methods and creation are all working correctly.
Example lines of text:
DONATION,ADD,101,1,Payroll deduction,22.22,07/04/1776,Y,1001
DONATION,ADD,303,3,Anniversary contribution,111.00,07/04/1777,N,2244
You have a typo
else if ( lineValues[0].equals("Donation")) {
should be
else if ( lineValues[0].equals("DONATION")) {
I'm trying to access an (add) method in my arrayList class from a TUI class, which will add a user to my arrayList.
This is my TUI class.
import java.util.ArrayList;
import java.util.Scanner;
public class BorrowerTUI
{
private BorrowerList borrowerList;
private Scanner myScanner;
public BorrowerTUI()
{
myScanner = new Scanner(System.in);
BorrowerList borrowerList = new BorrowerList();
}
public void menu()
{
int command = -1;
while (command != 0)
{
displayMenu();
command = getCommand();
execute (command);
}
}
private void displayMenu()
{
System.out.println( "Options are" );
System.out.println( "Enter 1" );
System.out.println( "Enter 2" );
System.out.println( "Enter 3" );
System.out.println( "Enter 4" );
}
private void execute( int command)
{
if ( command == 1)
addBorrower();
else
if ( command == 2 )
getNumberOfBorrowers();
else
if ( command == 3)
quitCommand();
else
if ( command == 4)
quitCommand();
else
if ( command == 5)
quitCommand();
else
System.out.println("Unknown Command");
}
private int getCommand()
{
System.out.print ("Enter command: ");
int command = myScanner.nextInt();
myScanner.nextLine();
return command;
}
public void getNumberOfBorrowers()
{
int command = myScanner.nextInt();
System.out.println("We have" + borrowerList.getNumberOfBorrowers() + "borrowers");
}
public void quitCommand()
{
int command = myScanner.nextInt();
System.out.println("Application Closing");
System.exit(0);
}
public void addBorrower()
{
Borrower borrower = new Borrower();
borrowerList.addBorrower(borrower);
}
}
This is my array list class.
import java.util.ArrayList;
public class BorrowerList
{
private ArrayList<Borrower> borrowers;
public BorrowerList()
{
borrowers = new ArrayList<Borrower>();
}
public void addBorrower(Borrower borrower)
{
borrowers.add(borrower);
}
public int getNumberOfBorrowers()
{
return borrowers.size();
}
public boolean getBorrower(String libraryNumber)
{
for(Borrower borrower : borrowers)
borrower.getLibraryNumber();
return true;
}
public void getBorrower(int borrowerEntry)
{
if (borrowerEntry < 0)
{
System.out.println("Negative entry: " + borrowerEntry);
}
else if (borrowerEntry < getNumberOfBorrowers())
{
Borrower borrower = borrowers.get(borrowerEntry);
borrower.printBorrowerDetails();
}
else
{
System.out.println("No such entry: " + borrowerEntry);
}
}
public void getAllBorrowers()
{
for(Borrower borrower : borrowers)
{
borrower.printBorrowerDetails();
System.out.println();
}
}
public void removeBorrower(int borrowerEntry)
{
if(borrowerEntry < 0)
{
System.out.println("Negative entry :" + borrowerEntry);
}
else if(borrowerEntry < getNumberOfBorrowers())
{
borrowers.remove(borrowerEntry);
}
else
{
System.out.println("No such entry :" + borrowerEntry);
}
}
public boolean removeBorrower(String libraryNumber)
{
int index = 0;
for (Borrower borrower: borrowers)
{
if (libraryNumber.equals(borrower.getLibraryNumber()))
{
borrowers.remove(index);
return true;
}
index++;
}
return false;
}
public int search(String libraryNumber)
{
int index = 0;
for (Borrower borrower : borrowers)
{
if (libraryNumber.equals(borrower.getLibraryNumber()))
{
return index;
}
else
{
index++;
}
}
return -1;
}
}
But for some reason when I try to link this method in my TUI class using the code at the top, it is returning the error: ") expected after 'User'"
Can somebody help, thanks.
It is returning an error because the method addUser is expecting a User object as input. In your call of the function, you gave it the User type as if you were declaring a method. Try passing in just a user object like so:
public void addUser()
{
User user = new User();
userList.addUser(user);
}
i have created string arraylist in which i copied all the data from database. Then i removed one record from arraylist by using al.remove(1, null). Now i want to add record in the position on which there is no data. I mean i want to add data at the position where data is null. I did write al.set(position, "new") but its giving me run time error i.e. OutOfMemory. Pls help me. Thanks
import java.io.*;
import java.util.*;
public class DAOImpl implements DAO
{
String xs[];
List<String> al= new ArrayList<String>();
int value;
public void list()
{
try
{
BufferedReader br=new BufferedReader(new FileReader("insurance.db"));
String next;
while((next=br.readLine())!=null)
{
//System.out.println(next);
al.add(next);
}
for(int i=0;i<al.size();i++)
{
System.out.print(i+1+"] ");
String ar[]=(al.get(i)).split(":");
for(int q=0;q<3;q++)
{
System.out.print(ar[q]);
System.out.print(" ");
}
//System.out.println(al.get(i));
System.out.println("");
}
}
catch (FileNotFoundException ex)
{
ex.printStackTrace();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
public String[] readRecord(int recNo)
{
String stream=(al.get(x-1));
xs=stream.split(":");
return xs;
}
public void deleteRecord(int recNo)
{
int del=recNo;
al.set(del-1, null);
for(int i=0;i<al.size();i++)
{
if((al.get(i))==null)
{
continue;
}
else
{
System.out.print(i+1+"] ");
String ar[]=(al.get(i)).split(":");
for(int q=0;q<3;q++)
{
System.out.print(ar[q]);
System.out.print(" ");
}
System.out.println("");
}
}
}
public int addRecord()
{
for(int y=0;y<al.size();y++)
{
if((al.get(y))==null)
{
value=y+1;
}
if((al.get(y))==null)
{
al.add(y, "new");//m getting error here...
}
}
for(int i=0;i<al.size();i++)
{
if((al.get(i))==null)
{
continue;
}
else
{
System.out.print(i+1+"] ");
String ar[]=(al.get(i)).split(":");
for(int q=0;q<3;q++)
{
System.out.print(ar[q]);
System.out.print(" ");
}
System.out.println("");
}
}
return value;
}
}
and main method is as follow:
import java.io.*;
public class InsuranceMain
{
public static void main(String args[])throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
DAOImpl d=new DAOImpl();
d.list();
//deleterecord
System.out.println("Enter Record Number to delete record:");
int delete=Integer.parseInt(br.readLine());
d.deleteRecord(delete);
//addrecord
d.addRecord();//m getting error here
//readRecord
System.out.println("Enter Record Number:");
int s=Integer.parseInt(br.readLine());
String as[]=d.readRecord(s);
for(int v=0;v<as.length;v++)
{
System.out.println(as[v]);
}
}
}
short answer:
change this line:
al.add(y, "new");//m getting error here...
into
al.set(y, "new");
Reason:
if you al.add(y,"new"), then, all elements after y (inclusive) will be shifted right. So next time you meet the null again (y+1), you add another "new", do this loop no ending.
also it is not good if you changing the list's size within a for loop like this.
I have a program that creates a queue, enqueues objects to the queue and then dequeues them one by one if the queue is not empty. The problem I am having is that the queue comes up empty each time it is checked. Print is called on the queue after enqueuing each object and it prints the queue's contents just fine.
import java.util.*;
import java.io.*;
public class Processor2
{
private LinkedQueue queue = new LinkedQueue();
private int time = 0;
private int count = 100;
private int amount = 0;
private PrintWriter out;
private Person temp;
private boolean var;
private Random randomNum = new Random();;
private String turn;
private int popCount=0;
private int loopCount =0;
public void start()
{
amount = randomNum.nextInt(5);
amount += 5;
pop(amount, time);
sim();
}
public void pop(int num, int time)
{
for(int i=1; i<=num; i++)
{
Person pe = new Person(i, time, 0);
queue.enqueue(pe);
System.out.println(queue);
}
popCount += num;
}
public void sim()
{
try
{
out = new PrintWriter(new FileWriter("output.txt"));
while(loopCount<=100)
{
var = queue.isEmpty();
if(var=true)
{
System.out.println("queue is empty");
}
if(var=false)
{
Object temp = queue.dequeue();
double rand = Math.random();
if(rand < 0.5)
{
System.out.println("inside if else statement");
// does stuff with object //
loopCount++;
}
else
{
System.out.println("inside if else statement");
// does stuff with object //
loopCount++;
}
}
}
out.close();
}
catch (IOException ioe)
{
System.out.println("Error Writing to File: " + ioe);
}
}
}
there doesn't seem to be anything wrong with the queue's isEmpty() method, but here it is:
public boolean isEmpty()
{
if(count == 0)
{
return true;
}
else
{
return false;
}
}
var = queue.isEmpty();
if(var=true) // this line *sets* var to true
{
System.out.println("queue is empty");
}
If you change if (var=true) to if(var==true) or just if(var) you should see a different result
I was wondering how I would add a trace to the stack of this code that converts infix to postix for expressions.
class Node {
public Object data;
public Node next;
public Node () {
data =' '; next = null; }
public Node (Object val) {
data = val; next = null; }
}
public class LinkStack {
private Node top;
public LinkStack() {
top = null; }
public boolean empty(){
return top == null; }
public boolean full(){
return false;
}
public void push(Object e){
Node tmp = new Node(e);
tmp.next = top;
top = tmp;
}
public Object pop(){
Object e = top.data;
top = top.next;
return e;
}
public Object peek(){
Object e = top.data;
return e;
}
public void matching(String x)
{
LinkStack S=new LinkStack();
for(int i=0;i<x.length();i++)
{
char c=x.charAt(i);
if(c=='(')
S.push(c);
else
{
if(c==')')
if(S.empty())
System.out.println("NOT MATCHING !!!");
else
S.pop();
}
}
if(!S.empty())
System.out.println("NOT MATCHING !!!");
else
System.out.println("MATCHING !!!");
}
public void Evaluation(String x)
{
LinkStack S=new LinkStack();
for(int i=0;i<x.length();i++)
{
char c=x.charAt(i);
String s="0"+c;
if(c=='+')
{
int z=Integer.parseInt((String)S.pop())+Integer.parseInt((String)S.pop());
S.push(Integer.toString(z));
}
else if(c=='*')
{
int z=Integer.parseInt((String)S.pop())*Integer.parseInt((String)S.pop());
S.push(Integer.toString(z));
}
else if(c=='/')
{ int u=Integer.parseInt((String)S.pop());
int z=Integer.parseInt((String)S.pop())/u;
S.push(Integer.toString(z));
}
else if(c=='-')
{ int u=Integer.parseInt((String)S.pop());
int z=Integer.parseInt((String)S.pop())-u;
S.push(Integer.toString(z));
}
else
S.push(s);
}
System.out.println("THE POSTFIX = "+x);
System.out.println("THE RESULT = "+S.pop());
}
public void postfix(String x)
{
String output="";
LinkStack S=new LinkStack();
for(int i=0;i<x.length();i++)
{
char c=x.charAt(i);
if(c==('+')||c==('*')||c==('-')||c==('/'))
{while(!S.empty() && priority(S.peek())>= priority(c))
output+=S.pop();
S.push(c);
System.out.println(output);
}
else if(c=='(')
{
S.push(c);
}
else if(c==')')
{
while(!S.peek().equals('('))
output+=S.pop();
S.pop();
System.out.println(output);
}
else
{
output+=c;
System.out.println(output);
}
}
while(!S.empty())
output+=S.pop();
System.out.println("THE INFIX = "+x);
System.out.println("THE POSTFIX = "+output);
}
public int priority(Object x)
{
if(x.equals('+')||x.equals('-'))
return 1;
else if(x.equals('*')||x.equals('/'))
return 2;
else
return 0;
}
public static void main(String args[])
{
LinkStack s=new LinkStack();
s.postfix("x*y–z+(a–c/d)");
System.out.println("------------------------------------------");
s.matching("x*y–z+(a–c/d)");
System.out.println("------------------------------------------");
}
}
I am pretty much wanting to follow the contents of the stack throughout the conversion
There's no rocket science solution to this.
Just add System.err.println(...) calls at the relevant places. Or if you were doing this in production code (heaven forbid!) you might use a Logger instead of System.err.
(For the record, the term "stack trace" normally means a trace of a program's call stack, not a trace of what happens to some application-specific stack data structure. You might want to choose your terminology a little more carefully next time.)