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
Related
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;
}*/
}
I need help creating a method that loads pets. I am having difficulty
writing a while loop that reads the file pets.txt and stores it in an array
list and returns the total number of pets. Once I have the pets loaded I
need to create a method to print the list, a method to find the heaviest
pet and a method to find the average weight of the pets.
Here is what I have so far:
try {
inFile = new Scanner(new FileReader("pets.txt"));
} catch (FileNotFoundException ex) {
System.out.println("File data.txt not found");
System.exit(1);
}
int i = 0;
while (inFile.hasNext() && i < list.length) {
// cant figure out how to write this
i++;
}
inFile.close();
return i;
pets.txt looks like this:
muffin, bobby, 25.0, pug
tiny, seth, 22.0, poodle
rex, david, 40.0, lab
lucy, scott, 30.0, bulldog
The format of this information is
(name of pet, name of owner, weight, breed)
Solution
This is my solution to this problem with the methods that you mentioned that you wanted. I simply just create a pet class and create an arraylist of the pet object and add the pet objects to the list when I use the scanner to get the data from the file!
Pet Class
public class Pet {
//Fields Variables
private String pet_name;
private String owner_name;
private double weight;
private String breed;
//Constructor
public Pet (String name, String o_name, double weight, String breed) {
//Set the variable values
this.pet_name = name;
this.owner_name = o_name;
this.weight = weight;
this.breed = breed;
}
//Getter and setter
public String getPet_name() {
return pet_name;
}
public void setPet_name(String pet_name) {
this.pet_name = pet_name;
}
public String getOwner_name() {
return owner_name;
}
public void setOwner_name(String owner_name) {
this.owner_name = owner_name;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public String getBreed() {
return breed;
}
public void setBreed(String breed) {
this.breed = breed;
}
}
Main Class
public class Main {
//ArrayList
private static ArrayList<Pet> pets = new ArrayList<>();
public static void main (String [] args) {
try {
Scanner sc = new Scanner(new File("path/to/file.txt")).useDelimiter(", |\n");
while (sc.hasNext()) {
//Get the info for the pet
Pet pet;
String name = sc.next();
String owner_name = sc.next();
double weight = sc.nextDouble();
String breed = sc.next();
//Create the pet and add it to the array list
pet = new Pet (name, owner_name, weight, breed);
pets.add(pet);
}
sc.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//Add your custom pets here if you would like!
addNewPet ("muffy", "john", 30.0, "beagle");
//Custom Methods
printList();
findHeaviestPet();
findLightestPet();
getAveragePetWeight();
}
public static void printList () {
for (int i = 0; i < pets.size(); i++) {
System.out.println (pets.get(i).getPet_name()+" "+pets.get(i).getOwner_name()
+" "+pets.get(i).getWeight()+" "+pets.get(i).getBreed());
}
}
public static void findLightestPet () {
//So we know the value will be assigned on the first pet
double weight = Double.MAX_VALUE;
int petIndex = 0;
for (int i = 0; i < pets.size(); i++) {
if (pets.get(i).getWeight() < weight) {
weight = pets.get(i).getWeight();
petIndex = i;
}
}
System.out.println("The lightest pet is "+pets.get(petIndex).getPet_name()+", with a weight of "+pets.get(petIndex).getWeight());
}
public static void findHeaviestPet () {
double weight = 0.0;
int petIndex = 0;
for (int i = 0; i < pets.size(); i++) {
if (pets.get(i).getWeight() > weight) {
weight = pets.get(i).getWeight();
petIndex = i;
}
}
System.out.println("The heaviest pet is "+pets.get(petIndex).getPet_name()+", with a weight of "+pets.get(petIndex).getWeight());
}
public static void getAveragePetWeight() {
double weights = 0;
for (int i = 0; i < pets.size(); i++) {
weights += pets.get(i).getWeight();
}
weights = (weights / pets.size());
System.out.println ("The average weight is "+weights);
}
public static void addNewPet (String name, String o_name, double weight, String breed) {
Pet pet = new Pet(name, o_name, weight, breed);
pets.add(pet);
}
}
Pets.txt
Please make sure that between every item there is a command and space like this ", " that is so we know when the next item is.
muffin, bobby, 25.0, pug
tiny, seth, 22.0, poodle
rex, david, 40.0, lab
lucy, scott, 30.0, bulldog
name, owner_name, 65.0, breed
In your loop you iterate over every line of the file. So you have to parse the line in it´s content (Split) and then save the informations in
Second you should create an Pet-Object (Objects and Classes) and save the information in each object. Your arraylist contains the created objects.
If you got some specific code, maybe someone will give you a more specific help.
What you have done so far is too "load" the file. You must now use the inFile (the scanner object) to access the contents of the pets.txt. This can be done in many ways such as using inFile.nextLine() (see the Javadocs).
Thereafter use string methods such as split() (again see the docs) to extract whichever parts of the string you want in the necessary format, to store in a Pets class.
You should then store each Pets object in a data structure (e.g. list) to enable you to write the methods you need in an efficient manner.
Pet Class
Public class Pet {
Public Pet(String pet_name, String owner, float weight, String breed) {
this.pet_name = pet_name;
this.owner = owner;
this.weight = weight;
this.breed = breed;
}
String pet_name;
String owner;
float weight;
String breed;
//implements getters and setters here
}
File reading method
private void read_file() throws Exception {
Scanner scanner = new Scanner(new FileReader("filename.txt"));
List<Pet> list = new ArrayList<>();
while (scanner.hasNextLine()) {
String[] data = scanner.nextLine().split(",");
Pet pet = new Pet(data[0], data[1], Float.valueOf(data[2]), data[3]);
list.add(pet);
}
}
First of all I would not read the data into a simple array list. I would probably use an ArrayList of classes. So I would declare a second class something like this:
//Declare pet class
class Pet{
// Can be either public or private depending on your needs.
public String petName;
public String ownerName;
public double weight;
public String breed;
//Construct new pet object
Pet(String name, String owner, double theWeight, String theBreed){
petName = name;
ownerName = owner;
weight = theWeight;
breed = theBreed;
}
}
Then back in whatever your main class is I would make the following method:
public ArrayList<Pet> loadFile(String filePath){
ArrayList<Pet> pets = new ArrayList<Pet>();
File file = new File(filePath);
try {
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
String s[] = sc.nextLine().split(",");
// Construct pet object making sure to convert weight to double.
Pet p = new Pet(s[0],s[1],Double.parseDouble(s[2]),s[3]);
pets.add(p);
}
sc.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
return pets;
}
I'm trying to call addContact method from main method using ArrayList called phone but its not working.
Here's the code:
import java.util.ArrayList;
import java.util.Scanner;
class A {
String name;
int num;
Scanner sc = new Scanner(System.in);
public A(String name, int num) {
this.name= name;
this.num= num;
}
public void addContact() {
sc.nextLine();
System.out.println("Enter name:");
name = sc.nextLine();
System.out.println("Enter number:");
num = sc.nextInt();
}
}
public class Main {
static void menu() {
System.out.println("1. add");
System.out.println("2. break");
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList <A> phone;
while(true) {
menu();
int c = sc.nextInt();
if(c==1) {
phone.add().addContact();
//I'm trying to call addContact()
} else if(c==2) {
break;
}
}
}
}
Why I can't just call phone.add().addContact()?
import java.util.ArrayList;
import java.util.Scanner;
class A {
String name;
int num;
Scanner sc = new Scanner(System.in);
public A(String name, int num) {
this.name= name;
this.num= num;
}
}
public class Main {
static void menu()
{
System.out.println("1. add");
System.out.println("2. break");
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList <A> phone = new Arraylist<A>();
while(true)
{
menu();
int c = sc.nextInt();
if(c==1)
{
System.out.println("Enter name:");
String name = sc.nextLine();
System.out.println("Enter number:");
int num = sc.nextInt();
phone.add(new A(name,num));
}
else if(c==2)
{
break;
}
}
}
}
Just removed you addContact and placed in in the while. Now i create a new Instance of A and add it to the list. This should work now. Please post more precise Questions in the future.
You need to create an instance of your list:
ArrayList<A> phone = new ArrayList<>();
ArrayList <A> phone;
Should be:
ArrayList phone = new ArrayList();
Also, the add() method in this line
phone.add().addContact();
should contain an A object to add to the ArrayList.
you need to return object of A
public A addContact() {
sc.nextLine();
System.out.println("Enter name:");
name = sc.nextLine();
System.out.println("Enter number:");
num = sc.nextInt();
return new A(name,num);
}
and
if(c==1)
{
phone.add(addContact);
}
Your problem starts here:
ArrayList <A> phone;
only declares that list; but doesnt define it. Thus you run into a NullPointerException when you try to run your code.
You need
ArrayList <A> contacts = new ArrayList<>();
instead. I took the freedom to give that variable a reasonable name, too. (this list is about storing contents, it is not storing phones; and it is also not a single phone ... just a list of contact information)
But there is more. You see, you are getting your abstractions wrong. Your Contact class (A is just a terrible name for that class) should not be dealing with a scanner to fetch its data.
Instead, you want to do something like:
class Contact {
private final String name;
private final int number;
Contact(String name, int number) {
this.name = name;
this.number = number;
}
and then, within your main method, you do something like:
boolean loop = true;
while (loop) {
... have user enter a name and a number
if (name.equals("STOP")) {
loop = false;
} else {
Contact contact = new Contact(name, number);
phones.add(contact);
}
}
I can't give the working code. Just check below points to make your program better.
Why you are creating constructor with arguments when you using add contact method.
Where you are created object for class A in class Main.
Try to check how to use ArrayList class. Because you are not using add() properly.
I am trying to create mutliple objects of a type of class I made. I then want to transfer these values into the array list. How can I create objects using a while loop that have different names. For example here is my code now, but it would only make an object of one name.
Customer cust = new Customer("bob", 20.0);
and my constructor if you want to see:
public Customer(String customerName, double amount)
{
String name=customerName;
double sale=amount;
}
StoreTest class (with main method):
import java.util.ArrayList;
import java.util.Scanner;
public class StoreTest {
ArrayList<Customer> store = new ArrayList<Customer>();
public static void main (String[] args)
{
double sale=1.0; //so the loop goes the first time
//switch to dowhile
Scanner input = new Scanner(System.in);
System.out.println("If at anytime you wish to exit" +
", please press 0 when asked to give " +
"sale amount.");
while(sale!=0)
{
System.out.println("Please enter the " +
"customer's name.");
String theirName = input.nextLine();
System.out.println("Please enter the " +
"the amount of the sale.");
double theirSale = input.nextDouble();
store.addSale(theirName, theirSale);
}
store.nameOfBestCustomer();
}
}
Customer class:
public class Customer {
private String name;
private double sale;
public Customer()
{
}
public Customer(String customerName, double amount)
{
name=customerName;
sale=amount;
}
}
Store class (has methods for messing with arraylist:
import java.util.ArrayList;
public class Store {
//creates Customer object and adds it to the array list
public void addSale(String customerName, double amount)
{
this.add(new Customer(customerName, amount));
}
//displays name of the customer with the highest sale
public String nameOfBestCustomer()
{
for(int i=0; i<this.size(); i++)
{
}
}
}
ArrayList<Customer> custArr = new ArrayList<Customer>();
while(youWantToContinue) {
//get a customerName
//get an amount
custArr.add(new Customer(customerName, amount);
}
For this to work... you'll have to fix your constructor...
Assuming your Customer class has variables called name and sale, your constructor should look like this:
public Customer(String customerName, double amount) {
name = customerName;
sale = amount;
}
Change your Store class to something more like this:
public class Store {
private ArrayList<Customer> custArr;
public new Store() {
custArr = new ArrayList<Customer>();
}
public void addSale(String customerName, double amount) {
custArr.add(new Customer(customerName, amount));
}
public Customer getSaleAtIndex(int index) {
return custArr.get(index);
}
//or if you want the entire ArrayList:
public ArrayList getCustArr() {
return custArr;
}
}
You can use this code...
public class Main {
public static void main(String args[]) {
String[] names = {"First", "Second", "Third"};//You Can Add More Names
double[] amount = {20.0, 30.0, 40.0};//You Can Add More Amount
List<Customer> customers = new ArrayList<Customer>();
int i = 0;
while (i < names.length) {
customers.add(new Customer(names[i], amount[i]));
i++;
}
}
}
I have some classes and I'm trying to fill the objects of this class. Here is what i've tried. (Question is at the below)
public class Team
{
private String clubName;
private String preName;
private ArrayList<String> branches;
public Team(String clubName, String preName)
{
this.clubName = clubName;
this.preName = preName;
branches = new ArrayList<String>();
}
public Team() {
// TODO Auto-generated constructor stub
}
public String getClubName() { return clubName; }
public String getPreName() { return preName; }
public ArrayList<String> getBranches() { return branches; }
public void setClubName(String clubName) { this.clubName = clubName; }
public void setPreName(String preName) { this.preName = preName; }
public void setBranches(ArrayList<String> branches) { this.branches = branches; }
}
public class Branch
{
private ArrayList<Player> players = new ArrayList<Player>();
String brName;
public Branch() {}
public void setBr(String brName){this.brName = brName;}
public String getBr(){return brName;}
public ArrayList<Player> getPlayers() { return players; }
public void setPlayers(ArrayList<Player> players) { this.players = players; }
}
//TEST CLASS
public class test {
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
String a,b,c;
String q = "q";
int brCount = 0, tCount = 0;
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
Team[] teams = new Team[30];
Branch[] myBranch = new Branch[30];
for(int z = 0 ; z <30 ;z++)
{
teams[z] = new Team();
myBranch[z] = new Branch();
}
ArrayList<String> tmp = new ArrayList<String>();
int k = 0;
int secim = Integer.parseInt(input.readLine());
while(secim != 0)
{
if(k!=0)
secim = Integer.parseInt(input.readLine());
k++;
switch(secim)
{
case 1 :
brCount = 0;
a = input.readLine();
teams[tCount].setClubName(a);
b= input.readLine();
teams[tCount].setPreName(b);
c = input.readLine();
while(c.equals(q) == false)
{
if(brCount != 0)
{c = input.readLine();}
if(c.equals(q)== false){
myBranch[brCount].brName = c;
tmp.add(myBranch[brCount].brName);
brCount++;
}
System.out.println(brCount);
}
teams[tCount].setBranches(tmp);
for(int i=0;i<=tCount;i++ ){
System.out.print("a :" + teams[i].getClubName()+ " " + teams[i].getPreName()+ " ");
System.out.println(teams[i].getBranches());}
tCount++;
break;
case 2:
String src = input.readLine();//LATERRRRRRRr
}
}
}
}
The problem is one of my class elements. I have an arraylist as an element of a class.
When i enter:
AAA as preName
BBB as clubName
c
d
e as Branches
Then as a second element
www as preName
GGG as clubName
a
b as branches
The result is coming like:
AAA BBB c,d,e,a,b
GGG www c,d,e,a,b
Which means ArrayList part of the class is putting it on and on. I tried to use clear() method but caused problems. Any ideas.
The problem is that the two Team objects are sharing the same reference to a single ArrayList<String>. There are many ways to solve this, but one way is to let Team manage its own List<Branch>, and it should only expose an add(Branch) instead of setBranches(List<Branch>). This would hide most information from the client, exposing only the most essential functionalities, which is a good thing.
Note also that I use the interface List<Branch> instead of ArrayList<Branch> (or ArrayList<String>). This is in accordance with Effective Java 2nd Edition, Item 52: Refer to objects by their interfaces.
I also recommend using java.util.Scanner for the I/O. Look at the API for examples, and there are many questions on stackoverflow about it as well. It'd make the code much simpler.
You need to copy lists in setters, otherwise you are using the same list (tmp) everywhere, so no wonder it has the same contents:
public void setBranches(List<String> branches) {
this.branches = new ArrayList<String>(branches);
}
public void setPlayers(List<Player> players) {
this.players = new ArrayList<Player>(players);
}
Theoretically, you also need to copy or wrap it in getters, but that's another story.