java hirerequest() and processhirerequest() methods - java

Hi guys i have created two different classes which are a shopitem class and a shopuser class, I need to create two methods, hirerequest() and processhirerequest: below is my attempt at coding which has been unsucessful and will not compile:
/**
* Accessor method hireRequest
*
* #return shopuser and shopitem object's
*/
public String hireRequest()
{
return shop item object;
return shop user object;
}
/**
* Accessor method processHireRequest
*
* #return name
*/
public String processHireRequest()
{
return hireRequest;
}
is this above code correct and should it work??
any answers or help would be greatly appreciated.
code Shopitem:
public abstract class ShopItem
{
private ArrayList<Tool> toolsList;
Shop shop;
private int toolCount;
private String toolName;
private int power;
private int timesBorrowed;
private boolean rechargeable;
private int itemCode;
private int cost;
private double weight;
private boolean onLoan;
private static JFrame myFrame;
private String Tool;
private String ElectricTool;
private String HandTool;
private String Perishable;
private String Workwear;
private boolean ShopUserID;
public void ReadToolData (String data) throws FileNotFoundException,NoSuchElementException
{
// shows the directory of the text file
File file = new File("E:/LEWIS BC 2/java project/project 1 part 3/ElectricToolData.txt");
Scanner S = new Scanner (file);
// prints out the data
System.out.println();
// prints out the
System.out.println();
S.nextLine();
S.nextLine();
S.nextLine();
S.nextLine();
S.nextInt ();
}
/**
* Creates a collection of tools to be stored in a tool list
*/
public ShopItem(String toolName, int power,int timesborrowed,boolean rechargeable,int itemCode,int cost,double weight,int toolcount,boolean onLoan,boolean ShopUserID)
{
toolsList = new ArrayList<Tool>();
toolName = new String();
power = 0;
timesborrowed = 0;
rechargeable = true;
itemCode = 001;
cost = 100;
weight = 0.0;
toolCount = 0;
onLoan = true;
// ShopUserID = null;
}
/**
* Default Constructor for Testing
*/
public ShopItem()
{
// initialise instance variables
toolName = "Spanner";
itemCode = 001;
timesBorrowed = 0;
power = 0;
onLoan = true;
rechargeable = true;
itemCode = 001;
cost = 100;
weight = 0.0;
toolCount = 0;
}
/**
* Reads ElectronicToolData data from a text file
*
* #param <code>fileName</code> a <code>String</code>, the name of the
* text file in which the data is stored.
*
* #throws FileNotFoundException
*/
public void readData(String fileName) throws FileNotFoundException
{
//
// while (there are more lines in the data file )
// {
// lineOfText = next line from scanner
// if( line starts with // )
// { // ignore }
// else if( line is blank )
// { // ignore }
// else
// { code to deal with a line of ElectricTool data }
// }
myFrame = new JFrame("Testing FileDialog Box");
myFrame.setBounds(200, 200, 800, 500);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setVisible(true);
{
FileDialog fileBox = new FileDialog(myFrame,
"Open", FileDialog.LOAD);
fileBox.setVisible(true);
}
{
File dataFile = new File(fileName);
Scanner scanner = new Scanner(dataFile);
while( scanner.hasNext() )
{
String info = scanner.nextLine();
System.out.println(info);
}
scanner.close();
}
}
/**
* Default Constructor for Testing
*/
public void extractTokens(Scanner scanner) throws IOException, FileNotFoundException
{
// extracts tokens from the scanner
File text = new File("E:/LEWIS BC 2/java project/project 1 part 3/items_all.txt");
String ToolName = scanner.next();
int itemCode = scanner.nextInt();
int cost = scanner.nextInt();
int weight = scanner.nextInt();
int timesBorrowed = scanner.nextInt();
boolean rechargeable = scanner.nextBoolean();
boolean onLoan = scanner.nextBoolean();
extractTokens(scanner);
// System.out.println(parts.get(1)); // "en"
}
/**
* Creates a tool collection and populates it using data from a text file
*/
public ShopItem(String fileName) throws FileNotFoundException
{
this();
ReadToolData(fileName);
}
/**
* Adds a tool to the collection
*
* #param <code>tool</code> an <code>Tool</code> object, the tool to be added
*/
public void storeTool(Tool tool)
{
toolsList.add(tool);
}
/**
* Shows a tool by printing it's details. This includes
* it's position in the collection.
*
* #param <code>listPosition</code> the position of the animal
*/
public void showTool(int listPosition)
{
Tool tool;
if( listPosition < toolsList.size() )
{
tool = toolsList.get(listPosition);
System.out.println("Position " + listPosition + ": " + tool);
}
}
/**
* Returns how many tools are stored in the collection
*
* #return the number of tools in the collection
*/
public int numberOfToolls()
{
return toolsList.size();
}
/**
* Displays all the tools in the collection
*
*/
public void showAllTools()
{
System.out.println("Shop");
System.out.println("===");
int listPosition = 0;
while( listPosition<toolsList.size() ) //for each loop
{
showTool(listPosition);
listPosition++;
}
System.out.println(listPosition + " tools shown" ); // display number of tools shown
}
public void printAllDetails()
{
// The name of the file to open.
String fileName = "ElectricToolDataNew.txt";
// This will reference one line at a time
String line = null;
try {
// FileReader reads text files in the default encoding.
FileReader fileReader =
new FileReader(fileName);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader =
new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
// Always close files.
bufferedReader.close();
}
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
fileName + "'");
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
}
code Shopuser
public abstract class ShopUser
{
private String name;
Shop shop;
private String shopUserID;
private String itemCode;
/**
* Constructor for objects of class ShopUser
*/
public ShopUser(String name, String shopUserID)
{
this.name = name;
this.shopUserID = shopUserID;
this.itemCode = itemCode;
}
// /**
// * Accessor method hireRequest
// *
// * #return shopuser and shopitem object's
// */
// public void hireRequest(String shopItem, String shopUser)
// {
// return shopItem;
// return shopUser;
// }
/**
* Accessor method getName
*
* #return name
*/
public String getName()
{
return name;
}
/**
* Accessor method getShopUserID
*
* #return shopUserID
*/
public String getShopUserID()
{
return shopUserID;
}
/**
* Method extractTokens that extracts tokens for a ShopUser object from a
* line of text that has been passed to the scanner
*
*/
public void extractTokens(Scanner scanner)
{
// data is name, shopUserID
name = scanner.next();
shopUserID = scanner.next();
}
/**
* Accessor method printDetails
*/
public void printDetails()
{
System.out.printf("%-15s %s %n", "name:", name);
System.out.printf("%-15s %s %n", "shop user ID:", shopUserID);
}
}

public String hireRequest() {
return shop item object;
return shop user object;
}
A method can only return ONE item.
Shop user object is never being called. You should have separate getters for shopUser and shopItem.

Related

"can only iterate over an array"

Link to Marks.txt file I was using for Student records for I/O: enter link description here
I have a Student class(contains 1 int studentID, and 6 assignment float scores) that is supposed to be filling another class called CourseSection (is just an ArrayList of Student objects), which is an ArrayList, with Student Objects.
So each Student Object should fill up the ArrayList called CourseSection after the data is read from a Marks.txt file.
I'm trying to write the search() method so it prompts the user for input of an StudentID, and then this int ID is used to traverse the ArrayList of Student objects until it .getID() == ID (the one the user input). THEN, it needs to display the corresponding students 6 assignment scores(floats). I'm getting a
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Can only iterate over an array or an instance of java.lang.Iterable
The error is coming from right after the for loop where is says "course2". Is java not reading this as an ArrayList? It's supposed to be an ArrayList of Student objects correct? because you can see I create the CourseSection object called "course2" first, then I read from the file Marks.txt and assign "course2" to equal this CourseSection.loadFrom method (which the method is returning a CourseSection object).
public static void search(){
BufferedReader aFile;
CourseSection course2 = new CourseSection(); //creates course object which is ArrayList of Student objects
aFile = new BufferedReader( new FileReader("marks_test_no_empty_strings.txt"));
course2 = CourseSection.loadFrom(aFile); // reads .txt into course ArrayList
Scanner scanner = new Scanner(System.in);
int id;
boolean foundStudent = true;
System.out.print("Enter the Student's ID: ");
id = enterID();
for(Student s : course2) {
if(s.getID() == id) {
s.getA1();
s.getA2();
s.getA3();
s.getA4();
s.getMidterm();
s.getFinalExam();
}
else
System.out.println("ID not found!!!");
}
}
and the CourseSection class if it helps:
import java.util.ArrayList;
import java.util.Iterator;
import java.io.*;
public class CourseSection {
private String name;
private ArrayList<Student> students;
/**
* Initializes the ArrayList<Student>.
*/
public CourseSection(String n)
{
name = n;
students = new ArrayList<Student>();
}
public CourseSection()
{
students = new ArrayList<Student>();
}
/**
* Will add a new student to the ArrayList.
* #param s A Student object.
*/
public void addStudent(Student s){
students.add(s);
}
/**
* Removes the selected student from the ArrayList.
* #param s A Student object.
*/
public void removeStudent(Student s){
Iterator studentIterator = students.iterator();
while(studentIterator.hasNext()){
if(studentIterator.next() == s)
studentIterator.remove();
}
}
/**
* Lists all the information for each student in the course section.
*/
public void listStudents(){
for(Student s: students){
System.out.println(s);
}
}
/**
* Reads aFile except for the header and continuously creates new student objects
* for a new CourseSection.
* #param aFile File to read from.
* #return CourseSection New CourseSection read from aFile
*/
public static CourseSection loadFrom(BufferedReader aFile) throws IOException{
//String line = aFile.readLine();
CourseSection course = new CourseSection(aFile.readLine());
aFile.readLine(); // skips line
while (aFile.ready()) //read until no more available (i.e., not ready)
{
course.addStudent(Student.loadFromST(aFile)); //read & add the student
}
return course;
}
}
This is the file I use to test the loadFrom methods in the Student class, and to test loadFrom in the CourseSection class
import java.io.IOException;
import java.util.InputMismatchException;
import java.util.Iterator;
import java.util.Scanner;
public class loadTester {
private static void studentLoadTest() throws IOException {
BufferedReader file1;
Student student1; // student object
//String line;
file1 = new BufferedReader(new FileReader("marks_test_no_empty_strings.txt"));
file1.readLine(); // skips 1st line
file1.readLine(); // skips 2nd line
/*
while(file1.ready())
{
System.out.println(file1.readLine());
}
*/
/* while((line = aFile.readLine()) != null) {
System.out.println(line);
}
*/
student1 = Student.loadFromST(file1); // using String Split
System.out.println(student1); // This method individually parses it
//file1.close();
}
private static void courseLoadTest() throws IOException {
//String line;
//CourseSection course = new CourseSection();
BufferedReader aFile = new BufferedReader(new FileReader("marks_test_no_empty_strings.txt"));
CourseSection course = CourseSection.loadFrom(aFile);
// course.loadFrom(aFile);
course.listStudents(); // this outputs the STUDENT OBJECTS IN THE ARRAY LIST!
//course = CourseSection.loadFrom(aFile);
//aFile.close();
}
public static void search(){
BufferedReader aFile;
CourseSection course2 = new CourseSection(); //creates course object which is ArrayList of Student objects
aFile = new BufferedReader( new FileReader("marks_test_no_empty_strings.txt"));
course2 = CourseSection.loadFrom(aFile); // reads .txt into course ArrayList
Scanner scanner = new Scanner(System.in);
int id;
boolean foundStudent = true;
System.out.print("Enter the Student's ID: ");
id = enterID();
for(Student s : course2) {
if(s.getID() == id) {
s.getA1();
s.getA2();
s.getA3();
s.getA4();
s.getMidterm();
s.getFinalExam();
}
else
System.out.println("ID not found!!!");
}
}
public static int enterID(){
Scanner scanner = new Scanner(System.in);
int id = 0;
try{
System.out.print("Enter the student's ID: ");
id = scanner.nextInt();
}catch(InputMismatchException e){
System.out.println("Error: InputMismatchException");
id = enterID();
}
return id;
}
public static void main(String[] args) throws IOException
{
System.out.println("Testing Student Object I/O Stream:");
studentLoadTest(); // testing to see if it outputs 1 Student Object per line
System.out.println();
System.out.println("Testing CourseSection creating ArrayList of Student Objects I/O Stream:");
courseLoadTest(); // this should output the Entire marks.txt file as an ArrayList of Student objects
search();
}
}
course2 is not iterable (CourseSection does not implements Iterable).
To iterate over course2's students, add a getter into CourseSection class :
public List<Student> getStudents() {
return this.students;
}
and iterate over it with
for(Student s : course2.getStudents()) {
}
The problem is that the CourseSection class is not iterable or an array. You can use it like that if you made this change:
public class CourseSection implements Iterable<Student> {
//adding the following method:
#Override
public Iterator<Student> iterator() {
return this.students.iterator();
}
You can also iterate directly over students by changing the calling code:
//You must add the getStudents() getter in CourseSection
for(Student s : course2.getStudents()) {
}
The CourseSection class is not a Array or list sot it won't compile try like this
CourseSection class:
import java.util.ArrayList;
import java.util.Iterator;
import java.io.*;
import java.util.Scanner;
public class CourseSection {
private String name;
private ArrayList<Student> students;
/**
* Initializes the ArrayList<Student>.
*/
public CourseSection(String n)
{
name = n;
students = new ArrayList<Student>();
}
public CourseSection()
{
students = new ArrayList<Student>();
}
/**
* Will add a new student to the ArrayList.
* #param s A Student object.
*/
public void addStudent(Student s){
students.add(s);
}
/**
* Removes the selected student from the ArrayList.
* #param s A Student object.
*/
public void removeStudent(Student s){
Iterator studentIterator = students.iterator();
while(studentIterator.hasNext()){
if(studentIterator.next() == s)
studentIterator.remove();
}
}
/**
* Lists all the information for each student in the course section.
*/
public void listStudents(){
for(Student s: students){
System.out.println(s);
}
}
public ArrayList<Student> getStudents()
{
return students;
}
/**
* Reads aFile except for the header and continuously creates new student objects
* for a new CourseSection.
* #param aFile File to read from.
* #return CourseSection New CourseSection read from aFile
*/
public static CourseSection loadFrom(BufferedReader aFile) throws IOException{
//String line = aFile.readLine();
CourseSection course = new CourseSection(aFile.readLine());
aFile.readLine(); // skips line
while (aFile.ready()) //read until no more available (i.e., not ready)
{
course.addStudent(Student.loadFromST(aFile)); //read & add the student
}
return course;
}
}
search method:
public static void search(){
BufferedReader aFile;
CourseSection course2 = new CourseSection(); //creates course object which is ArrayList of Student objects
aFile = new BufferedReader( new FileReader("marks_test_no_empty_strings.txt"));
course2 = CourseSection.loadFrom(aFile); // reads .txt into course ArrayList
Scanner scanner = new Scanner(System.in);
int id;
boolean foundStudent = true;
System.out.print("Enter the Student's ID: ");
id = enterID();
for(Student s : course2.getStudents()) {
if(s.getID() == id) {
s.getA1();
s.getA2();
s.getA3();
s.getA4();
s.getMidterm();
s.getFinalExam();
}
else
System.out.println("ID not found!!!");
}
}
Student class
public class Student {
private int ID;
private float a1;
private float a2;
private float a3;
private float a4;
private float midterm;
private float finalExam;
/**
* The Default constructor is used to intialize all instance variables
* in the class to zero.
*/
Student(){
ID = 0;
a1 = 0.0f;
a2 = 0.0f;
a3 = 0.0f;
a4 = 0.0f;
midterm = 0.0f;
finalExam = 0.0f;
}
Student(int id, float a1, float a2, float a3, float a4, float midterm, float finalExam) {
ID = id;
this.a1 = a1;
this.a2 = a2;
this.a3 = a3;
this.a4 = a4;
this.midterm = midterm;
this.finalExam = finalExam;
}
//Set methods for all instance variables of Student
public void setID(int newID)
{
ID = newID;
}
public void setA1(float newA1)
{
a1 = newA1;
}
public void setA2(float newA2)
{
a2 = newA2;
}
public void setA3(float newA3)
{
a3 = newA3;
}
public void setA4(float newA4)
{
a4 = newA4;
}
public void setMidterm(float newMidterm) // Typo was here for Mideterm
{
midterm = newMidterm;
}
public void setFinalGrade(float newFinal)
{
finalExam = newFinal;
}
//Get methods for instance variables of Student
public int getID()
{
return ID;
}
public float getA1()
{
return a1;
}
public float getA2()
{
return a2;
}
public float getA3()
{
return a3;
}
public float getA4()
{
return a4;
}
public float getMidterm()
{
return midterm;
}
public float getFinalExam()
{
return finalExam;
}
/**
* Prints all instance variables as a string.
* #return A string representing the student.
*/
public String toString(){
return(ID + ": " + a1 + " " + a2 + " " + a3 + " " + a4 + " " + midterm + " " + finalExam);
}
/**
* Will read from the linked file which will create and return a new Student object.
* #param aFile File to read from.
* #return A new Student object read from a line of the file.
* #throws IOException
* #throws NumberFormatException
*/
//using StringTokenizer
public static Student loadFromST(BufferedReader aFile) throws IOException {
Student newStudent = new Student();
//int i = 0;
//String zero = "0";
StringTokenizer st = new StringTokenizer(aFile.readLine()," ");
//while(st.hasMoreTokens()) {
//if(st.nextToken().isEmpty())
//zero = st.nextToken();
//else {
newStudent.ID = Integer.parseInt(st.nextToken());
newStudent.a1 = Float.parseFloat(st.nextToken());
newStudent.a2 = Float.parseFloat(st.nextToken());
newStudent.a3 = Float.parseFloat(st.nextToken());
newStudent.a4 = Float.parseFloat(st.nextToken());
newStudent.midterm = Float.parseFloat(st.nextToken());
newStudent.finalExam = Float.parseFloat(st.nextToken());
//i++;
//}
// }
return (newStudent);
}
//using Split String
/*
public static Student loadFromSS(BufferedReader aFile) throws java.io.IOException {
Student newStudent = new Student();
String[] words = aFile.readLine().split(" "); // can't split for anything bigger than 1 space
//for(int i = 0; i <= words.length; i++) {
// if(words[i].isEmpty())
// words[i] = "0";
// }
newStudent.ID = Integer.parseInt(words[0]);
newStudent.a1 = Float.parseFloat(words[1]);
newStudent.a2 = Float.parseFloat(words[2]);
newStudent.a3 = Float.parseFloat(words[3]);
newStudent.a4 = Float.parseFloat(words[4]);
newStudent.midterm = Float.parseFloat(words[5]);
newStudent.finalExam = Float.parseFloat(words[6]);
return newStudent;
}*/
}

Java prints only last entry of HashMap when run without debugger

I want my program print all the entries in HashMap, and it does if I run the app in debugger. But if I run it normaly it prints only the last entry :(
Have no idea why it does,
Please help me.
MoneyCounter:
package home.lib;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import home.interfaces.GoodsOper;
import home.interfaces.WalletOper;
import home.interfaces.WastesListOper;
public class MoneyCounter implements WastesListOper, WalletOper, GoodsOper {
private ArrayList<String> wastesPrint = new ArrayList<>();
private Map<GregorianCalendar, Good> wastesMap = new HashMap<GregorianCalendar, Good>();
private Map<String, Good> goodsMap = new HashMap<String, Good>();
private Map<String, Wallet> walletsMap = new HashMap<String, Wallet>();
private Wallet currentWallet;
private Good currentGood;
private SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-YYYY");
/**
* Provides selling (returning) of specified good puts the good
* to the wastesMap by date
* #param goodName
*/
#Override
public void sell(String goodName) {
// TODO implement the summation of wastes
if(goodsMap.containsKey(goodName)){
putMoney(goodsMap.get(goodName).getPrice());
wastesMap.put(new GregorianCalendar(), goodsMap.get(goodName));
}
}
/**
* Provides buying specified good puts the good you've bought
* to the wastesMap by date
* #param goodName
*/
#Override
public void buy(String goodName) {
// TODO implement the summation of wastes
if(goodsMap.containsKey(goodName)){
takeMoney(goodsMap.get(goodName).getPrice());
wastesMap.put(new GregorianCalendar(), goodsMap.get(goodName));
}
}
/**
* Add a new Wallet to the list if there is no the same one
* #param name
* #param currency
*/
#Override
public void createWallet(String name, String currency) {
walletsMap.putIfAbsent(name, new Wallet(name, currency));
}
/**
* Adds a new Good to the list with specified price
* #param name
* #param price
*/
#Override
public void createGood(String name, int price) {
goodsMap.putIfAbsent(name, new Good(name, price));
}
/**
* Returns array of strings with goods specifications, which
* satisfies the interval [startPrice, endPrice]
* #param startPrice
* #param endPrice
* #return array of strings String[]
*/
#Override
public String[] goodsListToStringByPrice(int startPrice, int endPrice) {
String[] goods = new String[goodsMap.size()];
int i = 0;
for (Map.Entry<String, Good> e : goodsMap.entrySet()) {
if (e.getValue().getPrice() >= startPrice && e.getValue().getPrice() <= endPrice) {
goods[i++] = e.getValue().goodToString();
}
}
return goods;
}
/**
* Returns an array of Strings with goods descriptions
* #return array of strings String[]
*/
#Override
public String[] goodsListToString() {
String[] goods = new String[goodsMap.size()];
int i = 0;
for (Map.Entry<String, Good> e : goodsMap.entrySet()) {
goods[i++] = e.getValue().goodToString();
}
return goods;
}
/**
* Replaces old Wallet's name with new one specified if one's name is absent
* #param oldName
* #param newName
*/
public void changeWalletName(String oldName, String newName) {
walletsMap.putIfAbsent(newName, new Wallet(newName, walletsMap.get(oldName)));
walletsMap.remove(oldName);
}
/**
* Returns an array of Strings with wallet descriptions
* #return array of strings String[]
*/
public String[] walletListToString() {
String[] wallets = new String[walletsMap.size()];
int i = 0;
for (Map.Entry<String, Wallet> e : walletsMap.entrySet()) {
wallets[i++] = e.getValue().walletToString();
}
return wallets;
}
/**
* Returns the wallet's money balance by name
* #param walletName
* #return String
*/
public String checkWallet(String walletName) {
return walletsMap.get(walletName).walletToString();
}
/**
* Deletes the wallet, specified by name from wallet list
* #param walletName
*/
#Override
public void delWallet(String walletName) {
walletsMap.remove(walletName);
}
/**
* Deletes the good, specified by name from good list
* #param goodName
*/
#Override
public void delGood(String goodName) {
goodsMap.remove(goodName);
}
/**
* Use this method to put more money to the wallet
* got payment for example
* #param count
*/
#Override
public void putMoney(int count) {
currentWallet.addMoney(count);
}
/**
* Use this method if you need money but not for buying a good
* #param count
*/
#Override
public void takeMoney(int count) {
currentWallet.getMoney(count);
}
/**
* Returns list of all wallets
* #return ArrayList
*/
#Override
public ArrayList<String> walletsListToString() {
ArrayList<String> array = new ArrayList<>();
for (Map.Entry<String, Wallet> entry : walletsMap.entrySet()) {
array.add(entry.getValue().walletToString());
}
return array;
}
/**
* Returns list of wallets specified by currency
* #param currency
* #return ArrayList
*/
#Override
public ArrayList<String> walletsListToStringByCurrency(String currency) {
ArrayList<String> array = new ArrayList<>();
for (Map.Entry<String, Wallet> entry : walletsMap.entrySet()) {
if (entry.getValue().getCurrency().equals(currency)) {
array.add(entry.getValue().walletToString());
}
}
return array;
}
/**
* Chooses wallet to operate with when you bus, sell, etc.
* #param walletName
*/
#Override
public void chooseTheWallet(String walletName) {
if (walletsMap.containsKey(walletName)) {
this.currentWallet = walletsMap.get(walletName);
}
}
/**
* Returns list of strings of all money wastes you've ever done
* #return ArrayList wastesPrint
*/
#Override
public void wastesListFillUp() {
for(Map.Entry<GregorianCalendar, Good> entry:wastesMap.entrySet()){
this.wastesPrint.add(dateFormat.format(entry.getKey().getTime())+" "+entry.getValue().goodToString()+
" "+currentWallet.walletToString());
}
}
/**
* Is used for tests
* #throws IOException
*/
public void printAllList() throws IOException {
for (Map.Entry<GregorianCalendar, Good> entry : wastesMap.entrySet()) {
System.out.println(dateFormat.format(entry.getKey().getTime())+" "+entry.getValue().goodToString()+
" "+currentWallet.walletToString());
}
}
/**
* Changes the specified good's price
* #param price
*/
#Override
public void changePrice(int price) {
currentGood.changePrice(price);
}
/**
* Chooses the good for operations
* #param goodName
*/
#Override
public void chooseTheGood(String goodName) {
if (goodsMap.containsKey(goodName)) {
this.currentGood = goodsMap.get(goodName);
}
}
}
Main:
package home.main;
import java.io.IOException;
import home.lib.MoneyCounter;
public class Main {
public static void main(String[] args) throws IOException {
MoneyCounter application = new MoneyCounter();
application.createGood("Snikers", 850);
application.createGood("Хрень какая-то", 1000);
application.createWallet("Основоной счет", "UAH");
application.chooseTheWallet("Основоной счет");
application.buy("Snikers");
application.buy("Хрень какая-то");
application.printAllList();
}
}
Wallet:
package home.lib;
public class Wallet {
// all money is kept
private int moneyCount;
private int debt;
private String currency;
private String name;
// constructor for new Wallet
public Wallet(String walletName, String currencyName) {
this.currency = currencyName;
this.moneyCount = 0;
this.debt = 0;
this.name = walletName;
}
// for renaming Wallet in WalletList
public Wallet(String walletName, Wallet oldWallet) {
this.name = walletName;
this.moneyCount = oldWallet.getMoneyCount();
this.debt = oldWallet.getDebt();
this.currency = oldWallet.getCurrency();
}
// actions with money
public void addMoney(int moneyCount) {
if (this.moneyCount >= 0 && this.debt == 0) {
this.moneyCount += moneyCount;
} else {
moneyCount -= this.debt;
this.debt = 0;
this.moneyCount = moneyCount;
}
}
public void getMoney(int moneyCount) {
if (this.debt == 0 && this.moneyCount > 0 && this.moneyCount >= moneyCount) {
this.moneyCount -= moneyCount;
} else {
moneyCount -= this.moneyCount;
this.moneyCount = 0;
this.debt += moneyCount;
}
}
// getters/setters block
public int getMoneyCount() {
return this.moneyCount;
}
public int getDebt() {
return this.debt;
}
public String getName() {
return this.name;
}
public String getCurrency() {
return this.currency;
}
public String walletToString() {
return this.debt <= 0 ? "("+this.name + " Остаток: " + (double)this.moneyCount/100 + " " + this.currency+")"
: "("+this.name + " Долг: -" + (double)this.debt/100 + " " + this.currency+")";
}
}
Good:
package home.lib;
public class Good {
private int price;
private String name;
public Good(String goodName, int goodPrice) {
this.name = goodName;
this.price = goodPrice;
}
public int getPrice() {
return this.price;
}
public double getPriceInDouble() {
return (double)this.price / 100;
}
public void changePrice(int price) {
this.price = price;
}
public String getName() {
return this.name;
}
public String goodToString() {
return "Товар: " + this.name + " | Цена: " + (double) this.price / 100;
}
}
I've got an answer. I used GregorainCalendar as a HashMap key. So, when I was starting program normaly, it was done in no time. So it was adding different values for ONE key. When you run the program in debugger you can't press next step 10 times in one moment so the time is different, so the keys are different too, so it returns all entries.
Be attentive when use time and all will be Ok :)

ArrayList is losing my reference

I have a static ArrayList (masterLog) that is in my main driver class. The ArrayList contains Event objects, the Event object has an ArrayList (heats) as a global variable. the heat object as an ArrayList (racers) as a global variable. Now when I have the following line of code:
System.out.println(ChronoTimer1009System.getMasterLog().get(0).getHeats().get(getCurHeat()).getRacers().toString());
this returns [] even though the getRacers() IS NOT empty!
When I call this:
System.out.println(getHeats().get(getCurHeat()).getRacers());
this returns the proper filled array.
I think I need to sync the masterLog ArrayList but I am unsure how. I have tried syncing it the way other threads on Stack Exchange have recommended but no luck.
it seems like the static ArrayList masterLog is updated two levels deep but not three levels deep if that makes sense.
What am I doing wrong?
UPDATE:
Maybe this will help explain:
In my main (driver) class, I have a static ArrayList called masterLog. The purpose of this ArrayLIst is to store instances of Event objects for later data retrieval. Now, without making it too complicated, the Event class contains an ArrayList called heats, and the Heat class contains an ArrayList called racers. When I access the masterLog ArrayList at some point in the program (when the other ArrayLists are populated with data), say for example by the call "masterLog.getHeats().get(0).getRacers()", the masterLog does not find any data in the racers ArrayList. It does, however, find data in the heats ArrayList. In other words, the object instance that is stored in the masterLog only updates information to a depth of 2 (not 3 if that makes sense).
UPDATE:
Here is some code:
ChronoTimer1009System class (driver)
package main;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Stack;
public class ChronoTimer1009System {
private Event curEvent;
private static Channel[] channels = new Channel[8];
private boolean state;
private static Stack<Log> log;
private static ArrayList<Event> masterLog;
private static Printer p;
public static Time globalTime;
private int oldLogSize; //used only in this.export()
public ChronoTimer1009System() throws UserErrorException{
for(int i=0; i<channels.length; ++i){channels[i] = new Channel(SensorType.NONE);} // initialize channels
masterLog = new ArrayList<Event>(); //this holds references to each event
this.newEvent(EventType.IND);
this.state = false; //system is initally off
log = new Stack<Log>();
p = new Printer();
globalTime = null;
oldLogSize = 0;
}
public void newEvent(EventType e) throws UserErrorException {
switch(e){
case IND: this.curEvent = new IND();ChronoTimer1009System.masterLog.add(this.curEvent);break;
case PARIND: this.curEvent = new PARIND();ChronoTimer1009System.masterLog.add(this.curEvent);break;
case GRP: this.curEvent = new GRP();ChronoTimer1009System.masterLog.add(this.curEvent);break;
case PARGRP: this.curEvent = new PARGRP();ChronoTimer1009System.masterLog.add(this.curEvent);break;
}
for(Channel x : channels){if(x.getState()) x.toggleState();}
}
public void on() throws UserErrorException{
if(state) throw new IllegalStateException();
this.curEvent = new IND();
ChronoTimer1009System.globalTime = new Time(0);
state = true;
}
public void reset() throws UserErrorException{
if(state) state = false;
on();
}
public void exit(){
this.curEvent = null;
ChronoTimer1009System.globalTime = null;
if(!state) throw new IllegalStateException();
state = false;
}
public static Time searchElapsedByID(int idNum){
Time toReturn = null;
for(Log item : log){
if(item.getCompetitorNumber() == idNum){
toReturn = item.getElapsedTime(); break;
}
}
return toReturn;
}
/**
* #return the curEvent
*/
public Event getCurEvent() {
return curEvent;
}
/**
* #return the state
*/
public boolean isState() {
return state;
}
public static Channel getChan(int chan){
if(chan < 1 || chan > 8) throw new IllegalArgumentException("Argument is not in range");
return channels[chan-1];
}
public static void export(){
//*****FORMAT JSON*****
//before formating, a sort of the runners within each heat is needed to determine place.
String toJson = "{\"events\":[";
System.out.println(ChronoTimer1009System.getMasterLog().get(0).getHeats().get(0).getRacers().size());
//iterate through each event
for(int i = 0; i < ChronoTimer1009System.getMasterLog().size(); ++i){
//iterate through each heat of each event
toJson += "{\"name\":\"" + ChronoTimer1009System.getMasterLog().get(i).getType().toString() + "\",\"heats\":[";
for(int j = 0; j < ChronoTimer1009System.getMasterLog().get(i).getHeats().size(); ++j){
//iterate through each competitor in each heat
toJson += "{\"runners\":[";
System.out.println(ChronoTimer1009System.getMasterLog().get(i).getHeats().size());
ArrayList<Competitor> x = sortByPlace(ChronoTimer1009System.getMasterLog().get(i).getHeats().get(j).getRacers()); <----- on this line, the getRacers() part has a size of zero when it isn't empty.
for(int k = 0; k < x.size(); ++k){
//notice we are working with a sorted copy
//TODO make Competitor endTime the elapsed time
toJson += "{\"place\":\"" + String.valueOf(k+1) + "\",\"compNum\":\"" + x.get(k).getIdNum() + "\", \"elapsed\":\"" + x.get(k).getEndTime().toString() + "\"},";
}
toJson += "]},";
}
toJson += "]},";
}
toJson += "}";
System.out.println(toJson);
/*try{
URL site = new URL("http://7-dot-eastern-cosmos-92417.appspot.com/chronoserver");
HttpURLConnection conn = (HttpURLConnection) site.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
String data = "data=" + toJson;
out.writeBytes(data);
out.flush();
out.close();
System.out.println("Done sent to server");
new InputStreamReader(conn.getInputStream());
}
catch (Exception e)
{
e.printStackTrace();
}*/
}
private static ArrayList<Competitor> sortByPlace(ArrayList<Competitor> unsorted)
{
ArrayList<Competitor> whole = (ArrayList<Competitor>) unsorted.clone();
ArrayList<Competitor> left = new ArrayList<Competitor>();
ArrayList<Competitor> right = new ArrayList<Competitor>();
int center;
if(whole.size()==1)
return whole;
else
{
center = whole.size()/2;
// copy the left half of whole into the left.
for(int i=0; i<center; i++)
{
left.add(whole.get(i));
}
//copy the right half of whole into the new arraylist.
for(int i=center; i<whole.size(); i++)
{
right.add(whole.get(i));
}
// Sort the left and right halves of the arraylist.
left = sortByPlace(left);
right = sortByPlace(right);
// Merge the results back together.
merge(left,right,whole);
}
return whole;
}
private static void merge(ArrayList<Competitor> left, ArrayList<Competitor> right, ArrayList<Competitor> whole) {
int leftIndex = 0;
int rightIndex = 0;
int wholeIndex = 0;
// As long as neither the left nor the right arraylist has
// been used up, keep taking the smaller of left.get(leftIndex)
// or right.get(rightIndex) and adding it at both.get(bothIndex).
while (leftIndex < left.size() && rightIndex < right.size())
{
if ((left.get(leftIndex).getEndTime().compareTo(right.get(rightIndex)))<0)
{
whole.set(wholeIndex,left.get(leftIndex));
leftIndex++;
}
else
{
whole.set(wholeIndex, right.get(rightIndex));
rightIndex++;
}
wholeIndex++;
}
ArrayList<Competitor>rest;
int restIndex;
if (leftIndex >= left.size()) {
// The left arraylist has been use up...
rest = right;
restIndex = rightIndex;
}
else {
// The right arraylist has been used up...
rest = left;
restIndex = leftIndex;
}
// Copy the rest of whichever arraylist (left or right) was
// not used up.
for (int i=restIndex; i<rest.size(); i++) {
whole.set(wholeIndex, rest.get(i));
wholeIndex++;
}
}
/**
* #return the log
*/
public static Stack<Log> getLog() {
return log;
}
/**
* #return the masterLog
*/
public static ArrayList<Event> getMasterLog() {
return masterLog;
}
/**
* #return the p
*/
public static Printer getPrinter() {
return p;
}
}
Event Class:
package main;
import java.util.ArrayList;
public abstract class Event extends Display{
private ArrayList<Heat> heats;
private int curHeat; //private means only this class can modify, not the subclasses
private Competitor curComp;
private String name;
public Event(String name) throws UserErrorException{
this.name = name;
heats = new ArrayList<Heat>();
curHeat = -1;
curComp = null;
createRun();
}
/**
* This method will be used by all EventTypes and will not change
* regardless of the EventType.
* #throws UserErrorException
*/
public void createRun() throws UserErrorException{
heats.add(new Heat()); ++curHeat;
}
/**
* #return the heats
*/
public ArrayList<Heat> getHeats() {
return heats;
}
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #return the currentHeat
*/
public int getCurHeat() {
return curHeat;
}
/**
* #return the curComp
*/
public Competitor getCurComp() {
return curComp;
}
/**
* #param curComp the curComp to set
*/
public void setCurComp(Competitor curComp) {
this.curComp = curComp;
}
/* (non-Javadoc)
* #see Display#displayHeatNumber()
*/
#Override
public String displayHeatNumber() {
// TODO Auto-generated method stub
return "Heat: " + (curHeat+1);
}
/* (non-Javadoc)
* #see Display#displayFinished()
*/
#Override
public String displayFinished() {
String toReturn = "";
boolean noRunners = true;
for(Competitor x : getHeats().get(getCurHeat()).getRacers()){
if(x.getEndTime() != null){
toReturn += "\n" + x.getIdNum() + " " + (ChronoTimer1009System.searchElapsedByID(x.getIdNum()).equals(new Time(Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE)) ? "DNF" : ChronoTimer1009System.searchElapsedByID(x.getIdNum()).toString() + " F");
noRunners = false;
}
}
if(noRunners){toReturn = "no runners have finished";}
return toReturn;
}
public abstract void endRun() throws UserErrorException;
public abstract void trigChan(int chan, boolean dnf) throws UserErrorException;
public abstract void cancel(int ln) throws UserErrorException;
public abstract EventType getType();
}
Heat class:
package main;
import java.util.ArrayList;
public class Heat {
private ArrayList<Competitor> racers;
//private ArrayList<Competitor> racers;
private int currentCompetitor;
/**
* Constructor
*/
public Heat(){
racers = new ArrayList<Competitor>();
//racers = new ArrayList<Competitor>();
currentCompetitor = 0;
}
/**
* Set selected racer as next on to start
* #param racer the racer to start next
*/
public void setNextCompetitor(Competitor x){
int pos = racers.indexOf(x);
if(pos == -1 || pos<currentCompetitor) throw new IllegalArgumentException("Competitor not in the race! Please add first");
for(int i = pos; i>currentCompetitor; --i){
racers.set(i, racers.get(i-1));
}
racers.set(currentCompetitor, x);
}
/**
* Take the selected runner (the next runner) out from the race
* #param racer the runner to be cleared
*/
public void clearNextCompetitor() throws UserErrorException {
if(racers.size()-(currentCompetitor)<1) throw new UserErrorException("No runners to clear!");
for(int i = currentCompetitor+1; i<racers.size(); ++i){
racers.set(i-1, racers.get(i));
}
racers.remove(racers.size()-1);
}
/**
* basically a remove method
* #param x
*/
public void remove(Competitor x){
int pos = racers.indexOf(x);
if(pos < 0) throw new IllegalArgumentException("runner does not exists");
racers.remove(pos);
}
/**
* Swaps two runners positions in line
*/
public void swap() throws UserErrorException{
int count = 0;
for(Competitor x : racers){
if(x.getStartTime() == null) ++count;
}
if(count > 1 && currentCompetitor + 1 <= racers.size()){
Competitor first = racers.get(currentCompetitor);
Competitor second = racers.get(currentCompetitor+1);
racers.set(currentCompetitor, second);
racers.set(currentCompetitor+1, first);
}
else{
throw new UserErrorException("Not enough competitors to swap");
}
}
/**
* Add a competitor to the end of the current line of competitors if any
* #param x the competitor to add
*/
public boolean addCompetitor(Competitor x) throws UserErrorException{
if(x.getIdNum() < 0 || x.getIdNum() > 99999) throw new UserErrorException("ID number out of range");
if(x.getRunNum() < 0) throw new IllegalArgumentException("Run Num Out of range");
boolean add = true;
for(Competitor i : racers){
if(i.getIdNum() == x.getIdNum()){
add = false;
break;
}
}
if(add){
racers.add(x);
}
return add;
}
/**
* Retrieve the next competitor if there is one
* #return the next competitor
*/
public Competitor getNextCompetitor() throws UserErrorException{
if(!hasNextCompetitor()) throw new UserErrorException("There are no more competitors!");
while(racers.get(currentCompetitor).isCompeting()){++currentCompetitor;}
return racers.get(currentCompetitor++);
}
/**
* used to fix the order of the queue after cancel is called
*/
public void fix(EventType x){
switch(x){
case IND:
--currentCompetitor;
break;
case GRP: case PARGRP: case PARIND:
for(int i = 0; i<racers.size(); ++i){
if(racers.get(i).getStartTime() == null){
currentCompetitor = i;
break;
}
}
break;
}
}
/**
* Is there another competitor to go?
* #return whether or not there is another competitor to go.
*/
public boolean hasNextCompetitor(){
return currentCompetitor < racers.size();
}
/**
* Return a 1D array view of the competitors
* #return
*/
public ArrayList<Competitor> getRacers(){
return racers;
}
}
in the export method of the ChronoTimer1009System class, I point out where the error is and what is happening

Create several new objects within a for-loop in Java

I want to create several objects from a class in a for loop. but I don't know how to code it. What I have written creates a new object but it overwrites the previous object.
package assginment1_version4;
import java.util.*;
public class Client {
public static void main (String[] args) {
System.out.println ("this is a bill database");
System.out.println ("add a user?(Y/N)");
Scanner input = new Scanner(System.in);
String answer = input.nextLine ();
ArrayList ary = new ArrayList ();
for (int i=1 ; i < 100; i++) {
if (answer.equalsIgnoreCase("y")) {
Bill bill1 = new Bill();
System.out.println("user first name:");
bill1.setFname (input.nextLine());
System.out.println("user Last name:");
bill1.setLname (input.nextLine());
System.out.println ("add a user?(Y/N)");
answer = input.nextLine ();
} else if (answer.equalsIgnoreCase ("n")) {
if (Bill.getBillCounter () == 0) {
System.out.println ("the Database is empty");
break;
} else {
System.out.println ("Number of Users: "
+ Bill.getBillCounter ());
break;
}
} else {
while (!answer.equalsIgnoreCase ("n")
&& !answer.equalsIgnoreCase ("y")) {
System.out.println ("add a user?(Y/N)");
answer = input.nextLine ();
}
}
}
}
}
please help me to complete this code.
You're overriding them because you create a new Bill on each loop and never save them off anywhere. I believe you want to add them to your ArrayList:
First, you should add a type to your ArrayList:
ArrayList<Bill> ary = new ArrayList<Bill>();
Then, before you get the input from the user on whether or not to add a new Bill, you should add the current one to this list:
...
System.out.println("user Last name:");
bill1.setLname(input.nextLine());
ary.add(bill1);
...
You haven't used the ArrayList, you need to add the Bill's objects at the end of the for loop.
ary.add(bill1);
and add a type to your ArrayList
ArrayList<Bill> ary = new ArrayList<Bill>();
This is the Bill class.....
package assginment1_version2;
public class Bill {
/**
* Attributes of a bill
*/
private String firstName;
private String lastName;
private int paymentDeadline;
private int paymentCode;
private int billCode;
/**
* Attribute of Bill Class
*/
private static int BillCounter=0;
/**
* Methods of Bill class
* #return number of users
*/
/*public static int getBillCounter(){
return BillCounter;
}*/
/**
* Class Constructor
* #param Fname is the first name of user
* #param Lname is the last name of user
* #param Pdeadline is the deadline of paying the bill
* #param Pcode introduces the payment uniquely
* #param Bcode introduces the bill uniquely
*/
public Bill (){
BillCounter++;
}
/**
* FirstName methods
* method to set FirstName
* #param n is the input of setname method as a user name
*/
public void setFname (String n){
firstName=n;
}
// method to get FirstName
public String getFname (){
return firstName;
}
/**
* LastName methods
* method to set LastName
*/
public void setLname (String m){
lastName=m;
}
// method to get LastName
public String getLname(){
return lastName;
}
/**
* PaymentDeadline methods
* method to set PaymentDeadline
*/
public void setPaymentDeadline(int m){
paymentDeadline= m;
}
//method to get PaymentDeadline
public int getPaymentDeadline(){
return paymentDeadline;
}
/*
* PaymentCode methods
* Method to set PaymentCode
*/
public void setPaymentCode (int m){
paymentCode=m;
}
//method to get PaymentCode
public int getPaymentCode(){
return paymentCode;
}
/*
* Methods of BillCode
* method to set BillCode
*/
public void setBcode(int Bcode){
billCode=Bcode;
}
//method to get BillCode
public int getBcode(){
return billCode;
}
}

Value isn't getting stored in Array?

I have four classes. Project Class, Student Class, ProjectFile Class and ProjectFrame JFrame.
The ProjectFrame is only for GUI and i haven't touched that.
The Student and Project Class are constructors and i've coded those.
Now i'm trying to implement the ProjectFile class by reading from a text file and then storing the data to be read. I am having trouble as i'm not sure why the Instance of the Project Class isn't storing the data. I've looked at my loops and i did print the variables to be sure that the loop is actually happening. It works for the first time but when i try to call the second array, it gives me a NullPointerException. So i'm assuming it's storing the value as null but that shouldn't be the case.
This is my ProjectFile Class
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package DecelAssignment;
import java.io.*;
/**
*
* #author Zane
*/
public class ProjectFile {
private static Project[] pJect;
private static Student[] sDent;
private static Project ja;
private static BufferedReader br;
public static void readData() {
File inputFile = new File("projects.txt");
try {
br = new BufferedReader(new FileReader(inputFile));
String s = br.readLine();
pJect = null;
pJect = new Project[Integer.parseInt(s)];
//System.out.println(s);
for (int i = 0; i < pJect.length; i++) {
s = br.readLine();
if (s == null) {
break;
} else {
String sLine[] = s.split(",");
int count = 3;
// for (int i2 = 0; i2 < Integer.parseInt(sLine[3]); i2++) {
// sDent[i2] = new Student(sLine[count+1], sLine[count+2], sLine[count+3], sLine[count+4]);
// count += 4;
// }
pJect[i] = new Project(sLine[0], sLine[1], sLine[2], sDent);
System.out.println(pJect[1].getTitle());
System.out.println(sLine[0]);
System.out.println(i);
}
}
} catch (IOException e) {
System.out.println("I caught an IO Exception1");
}
// } catch (NullPointerException e) {
// e.printStackTrace();
// System.out.println("I caught a Null Pointer Exception!");
//
// }
}
// public Project[] getProjectInfo() {
//
//
// return;
// }
public static void main(String[] args) {
readData();
}
}
This is the text file i'm reading from
3
iPhone App,EEE,John Tan,1,P109520,Kelvin Tay,DBIT,M
iPad App,DMIT,Mark Goh,3,P106286,Felicia Wong,DIT,F,P101803,Rachel Chang,DIT,F,P100036,Lewis Poh,DBIT,M
Green Living,DMIT,Audrey Lim,2,P101234,Peter Chua,DIT,M,P103287,Ng Ming Shu,DISM,F
Can someone please explain to me where i'm coding this wrongly? I can't figure it out.
EDIT:
This is the Project Class
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package DecelAssignment;
/**
*
* #author Zane
*/
public class Project {
private String title, school, supervisor;
private Student[] stDent;
public Project() {
title = "";
school = "";
supervisor = "";
stDent = new Student[0];
}
public Student[] getStDent() {
return stDent;
}
public Project(String title, String school, String supervisor, Student[] stDent) {
this.title = title;
this.school = school;
this.supervisor = supervisor;
this.stDent = stDent;
}
public String getSchool() {
return school;
}
public void setSchool(String school) {
this.school = school;
}
public String getSupervisor() {
return supervisor;
}
public void setSupervisor(String supervisor) {
this.supervisor = supervisor;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
I guess your code crashes here
System.out.println(pJect[1].getTitle());
In the first loop pJect[1] will contain null which causes a crash
You probably intend
System.out.println(pJect[i].getTitle());

Categories

Resources