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;
}*/
}
Related
Hello i've these 3 classes:
Here i put the name of a student and the exams he gave
package traccia50719;
import java.util.*;
public class Lab {
public static void main(String[] args) {
Studente studente = inserimento();
System.out.println("fine inserimento\n");
studente.print();
System.out.println("\nfine programma");
}
private static Studente inserimento() {
Studente s = null;
Esame esame=null;
System.out.println("\nmatricola:");
Scanner mat = new Scanner(System.in);
int matricola= mat.nextInt();
System.out.println("\ncognome:");
Scanner cog = new Scanner(System.in);
String cognome= cog.next();
System.out.println("\nNome:");
Scanner nom = new Scanner(System.in);
String nome= nom.next();
s= new Studente(matricola, cognome, nome);
do{
System.out.println("\ncodice esame:");
Scanner cod = new Scanner(System.in);
int codicesame= cod.nextInt();
if(codicesame==0){
break;
}
System.out.println("\nNome esame:");
Scanner nomes = new Scanner(System.in);
String nomesame= nomes.next();
System.out.println("\nvoto esame:");
Scanner vot = new Scanner(System.in);
int votoesame= vot.nextInt();
esame = new Esame(codicesame,nomesame,votoesame);
s.addEsame(esame);
}while(true);
return s;
}
}
In this class i've the student with the constructor but when i try to print exams with iterator i have only one exam printed. Why?
package traccia50719;
import java.util.*;
public class Studente {
private int matricola;
private String cognome;
private String nome;
private Set<Esame> esami = new TreeSet<Esame>();
public Studente(int matricola, String cognome, String nome){
this.matricola=matricola;
this.cognome=cognome;
this.nome=nome;
}
public void addEsame(Esame e){
this.esami.add(e);
}
public void print(){
System.out.println("\nmatricola:" + this.matricola);
System.out.println("\ncognome:" + this.cognome);
System.out.println("\nnome:" + this.nome);
Iterator<Esame> i = this.esami.iterator();
while(i.hasNext()){
Esame e = (Esame) i.next();
e.stampaesame();
}
}
}
This is the 3 class Exam and i've stampaEsame() that print name and the result of the exam
package traccia50719;
public class Esame implements Comparable{
private int codice;
private String nome;
private int voto;
public Esame(int codice, String nome, int voto){
this.codice=codice;
this.nome=nome;
this.voto=voto;
}
public void stampaesame(){
System.out.println("\n nome esame:" +this.nome);
System.out.println("\n voto esame:" +this.voto);
}
public boolean equals(Object o) {
Esame esa = (Esame) o;
if(this.codice==esa.codice){
return true;
}else return false;
}
public int compareTo(Object arg0) {
// TODO Auto-generated method stub
return 0;
}
}
Replace the line with esami like this.
private List<Esame> esami = new List<Esame>();
If it works like this, then the problem was with the way you override the hashCode() and equals() methods for the Esami class. Due to this TreeSet is treting all of your inserts as being the same element and as a set it can only contain one instance of the same element.
Remeber, hashCode() and equals() must be overridden together ;)
I am extremely stuck on this assignment I have, this is the last part of the assignment and it is going over my head. We were given this code to start off with.
import java.util.*;
import java.io.*;
public class TestEmployee2
{
public static void main(String[] args) throws IOException
{
Employee e1 = new Employee2(7, "George Costanza");
e1.setDepartment("Front Office");
e1.setPosition("Assistant to the Traveling Secretary");
e1.setSalary(50000.0);
e1.setRank(2);
e1.displayEmployee();
//Employee e2 = createEmployeeFromFile();
//e2.displayEmployee();
}
}
We were told to create a method called createEmployeeFromFile();. In this method we are to read from a .txt file with a Scanner and use the data to create an Employee object. Now I am confused on two things. First on the method type I should be using, and how to create an object with the data from the .txt file. This is the first time we have done this and it is difficult for me. Employee1 works fine, but when trying to create my method I get stuck on what to create it as.
Here is my rough draft code for right now.
import java.util.*;
import java.io.*;
public class TestEmployee2
{
public static void main(String[] args) throws IOException
{
EckEmployee2 e1 = new EckEmployee2(7, "George Costanza");
EckEmployee2 e2 = createEmployeeFromFile();
e1.setDepartment("Front Office");
e1.setPosition("Assistant to the Traveling Secretary");
e1.setSalary(50000.0);
e1.setRank(2);
e2.setNumber();
e2.setName();
e2.setDepartment();
e2.setPosition();
e2.setSalary();
e2.setRank();
e1.displayEmployee();
e2.displayEmployee();
}
createEmployeeFromFile(){
File myFile = new File("employee1.txt");
Scanner kb = new Scanner(myFile);
}
}
I am not expecting to get the answer just someone to point me in the right direction. Any help is greatly appreciated.
Here is my code from my main class.
public class EckEmployee2 {
private int rank;
private double number;
private double salary;
private String name;
private String department;
private String position;
public EckEmployee2() {
number = 0;
name = null;
department = null;
position = null;
salary = 0;
rank = 0;
}
public EckEmployee2(double number, String name) {
this.number = number;
this.name = name;
}
public EckEmployee2(double number, String name, String department, String position, double salary, int rank) {
this.number = number;
this.name = name;
this.department = department;
this.position = position;
this.salary = salary;
this.rank = rank;
}
public void setNumber(double num) {
this.number = num;
}
public double getNumber() {
return this.number;
}
public void setName(String nam) {
this.name = nam;
}
public String getName() {
return this.name;
}
public void setDepartment(String dept) {
this.department = dept;
}
public String getDepartment() {
return this.department;
}
public void setPosition(String pos) {
this.position = pos;
}
public String getPosition() {
return this.position;
}
public void setSalary(double sal) {
this.salary = sal;
}
public double getSalary() {
return this.salary;
}
public void setRank(int ran) {
this.rank = ran;
}
public int getRank() {
return this.rank;
}
public boolean checkBonus() {
boolean bonus = false;
if (rank < 5) {
bonus = false;
} else if (rank >= 5)
bonus = true;
return bonus;
}
public void displayEmployee() {
if (checkBonus() == true) {
System.out.println("-------------------------- ");
System.out.println("Name: " + name);
System.out.printf("Employee Number: %09.0f\n" , number, "\n");
System.out.println("Department: \n" + department);
System.out.println("Position: \n" + position);
System.out.printf("Salary: %,.2\n" , salary);
System.out.println("Rank: \n" + rank);
System.out.printf("Bonus: $\n", 1000);
System.out.println("-------------------------- ");
} else if (checkBonus() == false)
System.out.println("--------------------------");
System.out.println("Name: " + name);
System.out.printf("Employee Number: %09.0f\n" , number, "\n");
System.out.println("Department: " + department);
System.out.println("Position: " + position);
System.out.printf("Salary: %,.2f\n" , salary);
System.out.println("Rank: " + rank);
System.out.println("-------------------------- ");
}
}
To make things more clear here are the directions
Create a method in TestEmployee2 called createEmployeeFromFile() that will read data from a file and create, populate and return an Employee object. The file it will read from is called employee1.txt, which is provided. Hard code the name of the file in the method. This file contains the employee’s number, name, department, position, salary and rank. Create a Scanner object and use the Scanner class’s methods to read the data in the file and use this data to create the Employee object. Finally return the employee object.
In java, to return a value from a method, you add that objects type into the method signature as below, and in short java method signatures are as follows
'modifier (public, private, protected)' 'return type (void/nothing, int, long, Object, etc...' 'methodName(name the method)' 'parameters (any object or primitive as a parameter'
The method below will work if you have an employee contstructor which parses the input text, and assuming the data is split my a delimiter, you can use String.split(splitString); where splitString is the character that splits the data, i.e) a comma ",".
public EckEmployee2 getEmployee()
{
try
{
/**
* This will print where your java working directory is, when you run the file
*
*/
System.out.println(System.getProperty("user.dir"));
/**
* Gets the file
*/
File myFile = new File("employee1.txt");
/**
* Makes the scanner
*/
Scanner kb = new Scanner(myFile);
/**
* A list to store the data of the file into
*/
List<String> lines = new ArrayList<>();
/**
* Adds all the lines in the file to the list "lines"
*/
while (kb.hasNext())
{
lines.add(kb.next());
}
/**
* Now that you have the data from the file, assuming its one line here, you can parse the data to make
* your "Employee"
*/
if (lines.size() > 0)
{
final String line = lines.get(0);
return new EckEmployee2(line);
}
}
/**
* This is thrown if the file you are looking for is not found, it either doesn't exist or you are searching
* in the wrong directory.
*/
catch (FileNotFoundException e)
{
e.printStackTrace();
}
/**
* Return null if an exception is thrown or the file is empty
*/
return null;
}
First your method createEmployeeFromFile() must take 2 parameters, a Scanner object to read input, and the File you're gonna be reading from using the Scanner.
The return type is Empolyee2 because the method creates a Employee2 instance and must return it.
Now, I gave you the initiatives.
Your turn to read more about Scanner object and File object.
Reading from the text file, the attributes of your object, is easy then you create an instance by using the constructor with the attributes and return it!
Hope this helps.
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.
I am writing a simple program to list the name of the companies and the workforce in JAVA.
I would like to create objects dynamically. Below is the code
public class EmployeeRecord {
/**
* #param args
*/
String company, name;
int employee;
public String input;
public static BufferedReader br;
public int iE;
public static String numberOfCompanies;
String nameOfCompany;*/
public void company(String input) {
// TODO Auto-generated method stub
nameOfCompany = input;
}
public void employee(String employeeNumber) {
// TODO Auto-generated method stub
iE = Integer.parseInt(employeeNumber);
}*/
public static void main(String[] args) {
// TODO Auto-generated method stub
EmployeeRecord qw = new EmployeeRecord ();
try {
br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter number of companies: ");
numberOfCompanies = br.readLine();
int G = Integer.parseInt(numberOfCompanies);
for (int i = 1; i <= G; i++) {
System.out.println("Enter name of the company: ");
String company = br.readLine();
qw.company(company);
System.out.println("Enter Number of employees: ");
String employeeNumber = br.readLine();
qw.employee(employeeNumber);
}
for (int i = 1; i <= G; i++) {
qw.sortCompanySummary();
}
} catch (IOException io) {
io.printStackTrace();
}
}
public void companySummary() {
System.out.println("Number of companies: " + numberOfCompanies);
System.out.println("Name of company: "+nameOfCompany);
System.out.println("Number of employees: "+iE);
}
}
What I would like to do over here is create separate instances of the class EmployeeRecord dynamically. eg
EmployeeRecord qw = new EmployeeRecord();
EmployeeRecord we = new EmployeeRecord();
First, you need to separate out the object code from the controlling code.
Second, you need some sort of collection or array to hold your objects.
Here's an idea of how your code should look:
public class UI{ // <---- this class will control the flow of your program
public static void main(String[] args){
private List<Company> company; // <---- this Collection object holds many Company objects
...
for(int i=0;i<company.size();i++){
Company c = new Company();
c.setName(br.readLine());
List<Employee> employee = new ArrayList<Employee>();
...
for(int j=0;j<employee.size();j++){
Employee e = new Employee();
e.setName(br.readLine());
...
employee.add(e);
}
c.setEmployee(employee);
company.add(c);
}
}
}
public class Company{ // <---- this class will represent the companies
private List<Employee> employee;
private String name;
public void setEmployee(List<Employee> employee){
this.employee = employee;
}
....
}
public class Employee{ // <----- this class will represent the employees
private String name;
private int empNo;
public int getEmpNo(){
return empNo;
}
...
}
I did not understand the question correctly, but looking through the code, I believe you need to create objects in a loop as you are taking input from user. This is what you will need to do:
ArrayList<EmployeeRecord> qwList = new ArrayList<EmployeeRecord>();
Declare List before asking for input from user.
Now create the objects inside the loop, assign them values and add those objects to the list. This is what you can do inside the list
for (int i = 1; i <= G; i++) {
EmployeeRecord qw = new EmployeeRecord ();
System.out.println("Enter name of the company: ");
String company = br.readLine();
qw.company(company);
System.out.println("Enter Number of employees: ");
String employeeNumber = br.readLine();
qw.employee(employeeNumber);
qwList.add(qw);
}
For every company a new object has been inserted in the list. Now you can do whatever you want with this list. Either print all the records or sort them.
According to the code you posted and to the dynamic creation of objects you mentioned, I think the only way to do it is that you should take a look to the Collections Framework.
Collections Overview
Oracle Tutorials
Other Oracle Tutorials
Java2s Tutorials
I want to read a txt file and store each record in the file to an array of objects called data[]. Everything works except the record parts are not being assigned correctly in the data[].
This is the format for the record.txt...
4252 4 item1
2435 23 item2
4355 16 item3
so on and so on...
I want to keep using the methods I have been using even if there is an easier way (there always is).
Thank you much ...
import java.util.Scanner;
import java.io.*;
public class SortsTest
{
private static Data[] data;
private static String file_to_read;
private static int num_of_records,
current_record = 0;
private final static int RECORD_DATA = 3;
private static Scanner scan_file1;
public static void main(String[] args) throws IOException
{
try {
Scanner scan = new Scanner(System.in);
System.out.print("Enter a file name: ");
file_to_read = scan.next();
System.out.print("\nInput file = " + file_to_read);
System.out.print("\n# of records = ");
num_of_records = scan.nextInt();
scan_file1 = new Scanner(new File(file_to_read));
//---------------------- populate data array ------------------------
while (scan_file1.hasNext())
{
data = new Data[num_of_records];
String record[] = new String[RECORD_DATA];
for(int i = 0; i < RECORD_DATA; i++)
{
String line = scan_file1.next();
record[i] = line;
}
data[current_record] = new Data(record[0],record[1], record[2]);
current_record++;
}
//--------------------------------------------------------------------
//System.out.print("\n\nRecord 10: " + data[10].getPartName() + " " + data[10].getQuantity() + " " + data[10].getPartNumber());
System.out.print("\n\nRecord 10: " + data[10]);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
}
///////////////////////////// Data file /////////////////////////////////
import java.util.Scanner;
import java.io.*;
public class Data
{
private int part_num,
quantity;
private String part_name;
private Scanner scan_file1;
public Data(String part, String quan, String name)
{
part_num = Integer.parseInt(part);
quantity = Integer.parseInt(quan);
part_name = name;
}
public void setPartNumber(int num)
{
part_num = num;
}
public void setQuantity(int quan)
{
quantity = quan;
}
public void setPartName(String name)
{
part_name = name;
}
public int getPartNumber()
{
return part_num;
}
public int getQuantity()
{
return quantity;
}
public String getPartName()
{
return part_name;
}
}
You create a new empty data array every iteration through the while loop, try this:
data = new Data[num_of_records];
while (scan_file1.hasNext())
{
without going too deep into your code, I suspect this is part of your issue:
//---------------------- populate data array ------------------------
while (scan_file1.hasNext())
{
// you recreate your array every loop iteration
data = new Data[num_of_records];
instead, you need to do the following:
//---------------------- populate data array ------------------------
data = new Data[num_of_records];
while (scan_file1.hasNext())
{