I want to know how I can loop a new object within the same class, so that I can repeat the code to have several different objects with different details entered via the Scanner class.
It will probably make sense if I show what I am trying to do:
public class Students
{
private String studFirstName; // Student's first name
private String studSurname; // Student's surname
private String courseName; // Course name
public Students(String sFirstName, String sSurname, String cName)
{
studFirstName = sFirstName;
studSurname = sSurname;
courseName = cName;
}
public String getStudFirstName() // Getter for student's first name
{
System.out.println("Enter in student's first name: "); // Prompts end user for input
Scanner In = new Scanner(System.in); // Creating a new object
studFirstName = In.next(); // Accepts a one word input only
return studFirstName;
}
public String setStudFirstName(String sFirstName) // Setter for student's first name
{
return studFirstName;
}
public static void main (String [] args)
{
Students first[] = new Students[5];
for(Students a : first)
{
}
Students first[] = new Students("", "", "");
String studFirstName = first.getStudFirstName();
}
}
You need a regular for loop in order to assign values within the array.
int numStudents = 5;
Student students[] = new Student[numStudents]; // creates an array of 5 nulls
Scanner scan = new Scanner(System.in);
for(int i = 0; i < numStudents; i++) {
System.out.println("Enter your first name: "); // Prompt
String fname = scan.nextLine(); // Read
Student s = new Student(fname); // Assign
first[i] = s; // Store
}
You really don't need the get methods since you have access to set the values in the constuctor.
int numberOfStudents = 3;
// create an array that can hold up to 3 students
Student[] students = new Student[numberOfStudents];
// create the Scanner to read from console.
Scanner scanner = new Scanner(System.in);
// create the 3 students and store them in the array
for(int i = 0; i < numberOfStudents; i++) {
System.out.println("Enter name: ");
// read the next line from the console
String name = scanner.nextLine();
// ...
// if you have anything you need to create the student object (e.g. name, and so on).
Student s = new Student(studFirstName);
students[i] = s; // store the student object in the array.
}
// you should evt. close the scanner
// scanner.close();
// you can now do anything with your 3 stored students.
System.out.println("The Students first name is: " + students[0].getStudFirstName());
}
}
First, you should take a look at encapsulation. A getter is not meant to take user input. Getter should return the value of a private field. Setters should set the value of a private field.
// This is a field
private String myField;
// This will return the current value for the field 'myField'
public String getMyField() {
return this.myField;
}
// This will asign a new value to the field 'myField'
public void setMyField(String myField) {
this.myField = myField;
}
Answer
You will need a regular for loop to create as many students a you want. I renamed your class 'Students' to Student to fit javas naming conventions.
int numberOfStudents = 3;
// create an array that can hold up to 3 students
Student[] students = new Stundent[numberOfStudents];
// create the Scanner to read from console.
Scanner scanner = new Scanner(System.in);
// create the 3 students and store them in the array
for(int i = 0; i < numberOfStudents; i++) {
System.out.println("Enter name: ");
// read the next line from the console
String name = scanner.nextLine();
// ...
// if you have anything you need to create the student object (e.g. name, and so on).
Student s = new Student(name, .....);
students[i] = s; // store the student object in the array.
}
// you should evt. close the scanner
// scanner.close();
// you can now do anything with your 3 stored students.
System.out.println("The Students first name is: " + students[0].getStudFirstName());
Related
I'm not sure how to ask this question. I have to write a program that has 2 classes: one store the data and one call to display the data. The data is Student's name and the names of his/her 4 courses. But I have to put this in a loop for the user to input at least 3 records. If the user doesn't enter a student's name (or name = blank) get out of the loop and display the info entered.
Example:
John Doe MATH 101 ENGL 101 READ 101 COMP 101
Jane Doe PHYS 101 CHEM 101 PSYC 101 ACCT 101
Mary Doe PHED 101 HIST 101 CALC 101 POLS 101
What I'm trying to do is make each of the students' record an object and store those 3 objects in an array of objects then display it.
Below is my code:
import java.util.Scanner;
public class UserInterface {
public static void main(String[] args) {
//Create a scanner
Scanner input = new Scanner(System.in);
//Create an object from Business class
Business b = new Business();
//Declare variables
final int NUMBER_OF_COURSES = 4;
String[] coursesName = new String[4];
Business[] businessArray = new Business[3]; //Declare a array of objects
for (int counter = 0; counter < businessArray.length; counter++) {
//Prompt user to input name
System.out.println("Enter student's name: ");
b.setName(input.nextLine());
for (int i = 0; i < NUMBER_OF_COURSES; i++) {
System.out.println("Enter " + b.getName() + "'s course number " + (i + 1));
coursesName[i] = input.nextLine();
}//end of for(i)-loop
b.setCourses(coursesName);
businessArray[counter] = b;
System.out.println(businessArray[counter]); //Here it display correctly for each round
}//End of for(counter)-loop
for (int pa = 0; pa < businessArray.length; pa++)
System.out.println(businessArray[pa]); //but here it displays 3 records of the last entry
//so my question is how do I retain each entry in its own object and
//adds it to the array of objects?
//I know that b gets overwrite by the last data entered because
//it is just a pointer to that object.
input.close();
}//End of main method
}//End of class UserInterface
The other class:
public class Business {
//Declare variables
private String name;
private String[] courses = new String[4];
//Default Constructor
public Business(){
}
//getter for student's name
public String getName() {
return name;
}
//setter for student's name
public void setName(String name) {
this.name = name;
}
//getter for courses' name
public String[] getCourses() {
return courses;
}
//setter for courses' name
public void setCourses(String[] courses) {
this.courses = courses;
}
}//End of class Business
I know my codes are not good. But I'm required to have getters and setters for each variable in this Business class.
Move your creation of the Business object into the for loop:
for (int counter = 0; counter < businessArray.length; counter++) {
Business b = new Business();
// ...
}
Right now, every entry in the array points to the same object, so you're overwriting the values in it repeatedly. Moving the creation into the loop means you'll have a different object for each slot of the array.
String retainCourse(int pointer){
return this.courses[pointer];
}
Add this function to your business class.
You should overwrite the .toString() method of the class to get the expected result.
In a for loop it is a better practice to get the current object and set it as a temporary variable casted to the exact class! Business current = (Business) businesses[i];
I have a class that has private variables such as employeeName and employeeNumber and methods to set and get employeeName and employeeNumber. This class is called "EmployeesInformation". In this class I have two constructors. One that gets employee's information such as EmployeesInformation(String name, String phoneNumber){...} and another one that gets the same information but also receives two additional bits of information such as String datefired and String reasonForLeave.
Now in another class called "MenuOptionMethods" I have the addEmployee method and fireEmployee method and another method to show employees information.
I created two arrayList in this class called employee and formerEmployee.
Whenever the user adds an employee I put that employee object in the arrayList called employee. When the user fires or removes an employee I want to take all of that employee's information, remove it from arrayList employee and add it to arrayList formerEmployee. That is where I'm having problems. Can someone take a look at my code and tell me what's wrong with it?
public class menuOptionMethods {
Scanner sc = new Scanner(System.in);
private ArrayList<EmployeesInformation> employee;
private ArrayList<EmployeesInformation> formerEmployee;
public menuOptionMethods() {
employee = new ArrayList<EmployeesInformation>();
formerEmployee = new ArrayList<EmployeesInformation>();
}
public void addEmployee(String eName) {
String n = eName;
System.out.println(" Enter date hired: ");
String h = sc.next();
System.out.println(" Enter employee's duty: ");
String d = sc.next();
System.out.println(" Enter employee's phone number: ");
String pN = sc.next();
System.out.println(" Enter employee's pay per hour: ");
double pPH = sc.nextInt();
System.out
.println(" Enter any additional information about employee: ");
String l = sc.next();
EmployeesInformation e = new EmployeesInformation(n, h, d, l, pN, pPH);
employee.add(e);
}
public void fireEmployee(String eName) {
// System.out.println("Enter employee's name: ");
// String name = eName;
System.out.println("Reason for employee's leave?: ");
String reason = sc.next();
System.out.println("Enter date: ");
String dF = sc.next();
for(int i=0; i<employee.size(); i++){
if(employee.get(i).getEmployeName().contains(eName)){
n = eName;
h = employee.get(i).getDateHired();
d = employee.get(i).getEmployeDuty();
pH = employee.get(i).getPhoneNumber();
pPH = employee.get(i).getEmployePay();
l = employee.get(i).getAdditionalInformation();
employee.remove(i);
}
}
EmployeesInformation fE = new EmployeesInformation(n,h,d,l,pH,pPH,reason,dF); // ERROR HAPPENS HERE
}
}
You can't remove element from list while iterating it with for loop (it will throw ConcurrentModificationException. To do that, you need to use iterator and call remove() method, e.g.:
for(Iterator<Employee> iterator = employees.iterator() ; iterator.hasNext();){
Employee current = iterator.next();
if(current.getName().equals(name)){
iterator.remove();
//Add into former employees' list
break;
}
}
This will remove from existing list.
In your for loop, you don't want to do any removing because the size of the arraylist will change, and that just creates whack that is throwing you off. Assuming every employee has a unique name, you could do something like this (note I simplified making all those new variable by just transferring that employee object from one arraylist to the other):
int index;
for(int i=0; i<employee.size(); i++){
if(employee.get(i).getEmployeName().contains(eName)){
formerEmployee.add(employee[i]); //date fired and reason fired can be added later
index = i;
break;
}
}
employee.remove(i);
}
I am trying to assign the current array element in the temp array with the Student object returned after calling the getStudent method.... I called the getStudent method (Step 2) and have temp[i] = to assign the current element in the temp array but cannot figure out what it should = to pair it up with the Student object returned. When using getStudent() and running the program, the output is enter the number of students, the user enters the number, and that is all that happens, it does not ask for the user to enter the name and etc, I'm not sure if step 2 is the problem or if there is another issue entirely.
import java.util.Scanner;
public class Students
{
private static Scanner input = new Scanner(System.in);
public static void main(String[] args)
{
Student[] students;
students = getStudents();
printStudents(students);
}
private static Student[] getStudents()
{
Student[] temp;
int how_many;
System.out.print("How many students? ");
how_many = input.nextInt();
purgeInputBuffer();
temp = new Student[input.nextInt()]; // Step 1 ???
for (int i = 0; i < temp.length; i++)
{
getStudent(); // Step 2
temp[i] = ; // <----------
}
return temp; // Step 3
}
private static Student getStudent()
{
String name,
address,
major;
double gpa;
System.out.print("Enter name: ");
name = input.nextLine();
System.out.print("Enter address: ");
address = input.nextLine();
System.out.print("Enter major: ");
major = input.nextLine();
System.out.print("Enter GPA: ");
gpa = input.nextDouble();
purgeInputBuffer();
return new Student (name, address, major, gpa); // Step 4
}
private static void printStudents(Student[] s)
{
System.out.println();
for (int i = 0; i < s.length; i++) // Step 5
{
System.out.println(getStudent()); // Step 6
}
}
private static void purgeInputBuffer()
{
// ----------------------------------------------------
// Purge input buffer by reading and ignoring remaining
// characters in input buffer including the newline
// ----------------------------------------------------
input.nextLine();
}
}
So first problem is first on the line:
temp = new Student[input.nextInt()];
in that line you have already asked the user to enter how many Students and store it in how_many. So i'm assuming you want to instead do:
temp = new Student[how_many];
Also what i said in my comment:
But please do also look at your private static void printStudents(Student[] s) method and acutally on the line //step 6 i don't believe that is how you want to be doing that. Instead you want System.out.println(s[i]); not System.out.println(getStudent()); For my code substitution to work though you will need to Override the toString method so it can actually display the information
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have figured out how to gather the data from the user to make a new student in my array, but I am having trouble adding that information to the array. Please show me how I can add this data as a new Student object in the given code. Please reference to the AddStudent method.
import java.util.Scanner;
public class ArrayDemo {
static Student[] students;
private static void ViewStudents() {
for (int i = 0; i < students.length; i++) {
System.out.println(i + ") " + students[i].getLName() + ", " + students[i].getFName());
}
}
private static void ViewDetails() {
Scanner kb = new Scanner(System.in);
int i;
System.out.println("Who would you like to view?");
ViewStudents();
i = Integer.parseInt(kb.nextLine());
System.out.println("ANum:\t\t" + students[i].getANum());
System.out.println("\nAddress:\t" + students[i].address.getHouseNum() + " " + students[i].address.getStreet());
System.out.println("\t\t" + students[i].address.getCity() + ", " + students[i].address.getState() + " " + students[i].address.getZip());
System.out.println("\t\t" + students[i].address.getLine2());
}
private static void AddStudent() {
Scanner kb = new Scanner(System.in);
Student student = new Student();
String FirstName;
String LastName;
int HouseNum;
String Street;
String City;
String State;
int Zip;
String Line2;
System.out.println("\tInput Information");
System.out.println("\tFirst Name:");
FirstName = kb.nextLine();
System.out.println("\tLast Name:");
LastName = kb.nextLine();
System.out.println("\tHouse Number:");
HouseNum = Integer.parseInt(kb.nextLine());
System.out.println("\tStreet:");
Street = kb.nextLine();
System.out.println("\tCity:");
City = kb.nextLine();
System.out.println("\tState:");
State = kb.nextLine();
System.out.println("\tZip Code:");
Zip = Integer.parseInt(kb.nextLine());
System.out.println("\tExtra Information:");
Line2 = kb.nextLine();
System.out.println("\nStudent:\t" + LastName + ", " + FirstName);
System.out.println("ANum:\t\t" + student.getANum());
System.out.println("Address:\t" + HouseNum + " " + Street);
System.out.println("\t\t" + City + ", " + State + " " + Zip);
System.out.println("\t\t" + Line2);
//students.setAddress( HouseNum, Street, City, State, Zip, Line2 );
System.out.println("\tYour Student was Successfully Added");
}
private static void RemoveStudent() {
Scanner kb = new Scanner(System.in);
System.out.println("Who would you like to remove?");
ViewStudents();
for (int j = Integer.parseInt(kb.nextLine()); j < students.length - 1; j++) {
students[j] = students[j + 1];
}
students[students.length - 1] = null;
}
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
int x = 40;
//students = new Student[0];
students = new Student[2];
students[0] = new Student("Thomas", "Emily");
students[1] = new Student("Bob", "Joe");
students[0].address = new Address(6614, "White Sands ln", "Hixson", "Tennessee", 37343, "");
students[1].address = new Address(66, "White ln", "Hson", "Tealamabaee", 373873, "");
do {
System.out.println();
System.out.println("Do you want to:");
System.out.println("\t0) View Students");
System.out.println("\t1) View Students' Details");
System.out.println("\t2) Add a Student");
System.out.println("\t3) Remove a Student");
System.out.println("\t4) Exit");
x = Integer.parseInt(kb.nextLine());
switch (x) {
case 0:
ViewStudents();
break;
case 1:
ViewDetails();
break;
case 2:
AddStudent();
break;
case 3:
RemoveStudent();
break;
case 4:
break;
default:
}
} while (x != 4);
}
}
From what I can see, you are using the wrong kind of data structure. You seem to what to add a dynamic number of Students and an ArrayList would be a lot better and more appropriate than an Array. Then you can simply use the add method.
Remember, the size of an Array is immutable (it cannot change) so what you want in this case is definitely some sort of List, probably the ArrayList
If you insist on using an array, you would need to keep track of the number students already added and use that as an index (either as a global variable or pass it in as a parameter). But bear in mind that the nature of an Array means that you will hit a cap very quickly unless you set an very high capacity,
Believe me that there is no way you can add records to array without knowing how many records are there currently in your array. If you don't want another static variable to keep track number of records, you have to loop through the array till it is null.
static int numOfStudents = 0; //declare outside your main
public static void AddStudent()
{
Scanner scn = new Scanner( System.in );
if (numOfStudents < students.length){
System.out.println("Enter last name:");
String ln = scn.nextLine():
System.out.println("Enter first name:");
String fn = scn.nextLine():
Student stud = new Student(ln, fn);
students[numOfStudents] = stud;
numOfStudents ++;
}
}
An alternative solution which you would prefer. But this is bad in my opinion.
public static void AddStudent()
{
Scanner scn = new Scanner( System.in );
int index=0;
while(x<students.length && student[x] != null)
index++; //get position to add new student
System.out.println("Enter last name:");
String ln = scn.nextLine():
System.out.println("Enter first name:");
String fn = scn.nextLine():
Student stud = new Student(ln, fn);
students[index] = stud;
}
The easiest way without much change to your code would be to add a class variable called index next to the students array. This variable will keep track of the amount of students since arrays in Java have fixed length:
public class ArrayDemo
{
static Student[] students;
static int index = 0; // keeps track of the amount of students in the students array
// ... rest of your code
Then inside AddStudent() you add all the information you got from input to the current student at the index and update the index:
private static void AddStudent() {
// ... the code where you obtain user information
if(index < students.length) { // make sure there is room to add the user
Student student = new Student(/* add user information into the constructor */);
students[index] = student; // add the user at the index
index++; // update the index
} else {
System.err.println("No more room for students");
}
}
The code above assumes you have a constructor that accepts necessary user information.
Otherwise you can assign the information individually:
Student student = new Student();
student.firstName = firstName;
// ...
Or use setters like:
student.setFirstName(firstName);
If you do not with to use an index to keep track of amount of users and have a more dynamic way of storing the students, then I suggest using a List or some class that extends it such as an ArrayList
Your array has a fixed size of 2 elements. You could instead use a larger MAX value and (as the other answers have hinted) keep a variable that counts the actual number of array indices that are filled.
static int ARRAY_MAX = 10;
static Student[] students;
static int numStudents;
...
students = new Student[ARRAY_MAX];
numStudents = 0;
Adding a student would then look like...
students[numStudents] = new Student();
numStudents++;
...but its going to break when numStudents is greater than equal 10 (ArrayIndexOutOfBoundsException).
In this event you need to enlarge (resize) your array. In Java arrays have fixed size - resizing an array amounts to declaring a brand new array (with increased size), and then copying the old array into the new one. Use System.arraycopy to copy the contents from one array into the other.
You should really just use an ArrayList - behind the scenes this is what that object is doing.
I'm trying to reference the GPA in my StudentData class, however I'm getting an error that says it can't find the symbol on the line that says aStudent.gpa = studentGPA.
my main class:
public static void main (String [] args)
{
//local constants
final String QUIT = "Quit";
final String YES = "Y";
final int MODIFY_GPA = 1;
final int DISPLAY_USER = 2;
final int QUIT_MENU = 3;
//local variables
String name; //name of the user
String idPrompt; //asks the user if they want to input a gpa and id
String studentID; //student ID input by the user
float studentGPA; //student GPA input by the user
int choice; //prompts the user for a menu choice
Library myLib = new Library();
/****************** Start main method *******************/
//prompt for name of user or quit
System.out.print("Enter name of user(First and Last, Quit to end): ");
name = Keyboard.readString();
while(!QUIT.equals(name))
{
//ask the user if they want to enter ID and GPA
System.out.print("Do you want to enter an ID and GPA?(Y/N): ");
idPrompt = Keyboard.readString();
//if the user says yes
if(!YES.equals(idPrompt))
{
//instantiate a new Student with just the name
StudentData aStudent = new StudentData(name, "", 0);
}
else
{
//prompt the user for the ID
System.out.print("Enter the Student ID: ");
studentID = Keyboard.readString();
//prompt the user for the GPA
System.out.print("Enter the Student GPA: ");
studentGPA = Keyboard.readFloat();
//instantiate a new Student with all three data types
StudentData aStudent = new StudentData(name, studentID, studentGPA);
}
//clear the screen
myLib.clrscr();
//prompt user for a menu choice
choice = displayMenu();
//clear the screen
myLib.clrscr();
//begin while loop to modify the user or display
while(choice != QUIT_MENU)
{
//if the user wants to modify the GPA
if(choice == MODIFY_GPA)
{
studentGPA = StudentData.modifyGPA();
aStudent.gpa = studentGPA;
}
//if the user wants to display
else if(choice == DISPLAY_USER)
{
System.out.print("STUDENT OUTPUT");
//System.out.println(StudentData);
}
//if there was an invalid menu choice
else
{
System.out.print("INVALID DATA ENTERED");
}
//prompt for next choice
choice = displayMenu();
}
//prompt for name of user or quit
System.out.print("Enter name of user(First and Last, Quit to end): ");
name = Keyboard.readString();
}
}//end main method
and this is my StudentData class
public class StudentData
{
public String name;
public String id;
public float gpa;
//create a constructor that will receive the name of the student only
public StudentData(String inName)
{
//local variables
id = ""; //set the ID to null
gpa = 0.00F; //set the gpa to 0.00
name = inName; //gets the name of the student from the user
}
//create an overloaded constructor that will receive all three pieces of instance data
public StudentData(String inName, String inID, float inGPA)
{
name = inName; //name input by user through the constructor parameter
id = inID; //ID input by user through the constructor parameter
gpa = inGPA; //GPA input by user through constructor parameter
}
//create a method that will modify the students GPA
public static float modifyGPA()
{
//local constants
//local variables
float newGPA;
System.out.print("Enter new GPA: ");
newGPA = Keyboard.readFloat();
return newGPA;
}
//create a toString method that will format the instance data to look like:
public String toString()
{
String format;
format = ("Student" + name + "\n" +
"Student ID" + id + "\n" +
"Student GPA" + gpa + "\n");
return format;
}
It's the studentGPA variable. It's declared in a local block:
if(!YES.equals(idPrompt))
{
// variable *declared* here!
StudentData aStudent = new StudentData(name, "", 0);
// aStudent is visible here
}
// but it's not visible here out of the scope of this local block.
and thus only visible in that block. If you want it visible throughout the method, then declare it in method or class scope.
Scope, scope, scope!! Declarations in Java (and C/C++) are "scoped" to the "block", where a "block" is a set of statements between { and }.
This means that if you declare a variable { StudentData aStudent = new StudentData(...); } it goes "poof" when you pass that closing }. If you want it to be "visible" outside that scope you need to declare aStudent outside the block.
Note that you can still do the assignment inside that block, just don't mistakenly include StudentData or you will be declaring an entirely different version of the variable. And note that, in Java, a variable must be assigned a value along all possible paths from its declaration to its use, so you may have to assign null (eg) to the variable where it's declared.
for your posted problem,you can do like this in main class,
// your code
StudentData aStudent = null;
while(!QUIT.equals(name))
{
//your code
//if the user says yes
if(!YES.equals(idPrompt))
{
//instantiate a new Student with just the name
aStudent = new StudentData(name, "", 0);
}
else
{
//your code
//instantiate a new Student with all three data types
aStudent = new StudentData(name, studentID, studentGPA);
}
//your code