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];
Related
We are asked to write a code and enter name and age for 4 people. After that, we are required to find whether any of the age match each other. Later the question asks whether the names match, but I haven't gotten to that part just yet.
I tried making an array so that I can store the values of the inputted ages. I cannot figure out how I can compare age's values with other elements in the array.
package person;
public class Person
{
static int personAge;
String personName;
public void setName(String name) {
name=personName;
}
public String getName() {
return personName;
}
public void setAge(int age){
age=personAge;
}
public int getAge() {
return personAge;
}
}
package person;
import java.util.Scanner;
public class PersonMain extends Person
{
static int [] ageStore=new int [4];
public static void main(String[] args)
{
for(int i=1;i<5;i++)
{
Person person= new Person();
person.setName(person.personName);
System.out.println("Please enter name for person " + i );
Scanner input= new Scanner(System.in);
person.personName=input.next();
Scanner keyboard= new Scanner(System.in);
System.out.println("Now, input " + person.personName + "'s age" );
person.setAge(personAge);
personAge=keyboard.nextInt();
ageStore[i]=person.personAge;
System.out.println("Age is " + ageStore[i]);
}
//what can help me compare the values of int age in the array?
}
}
The end goal here is to print out the names of people that have the same age.
Of course they all have the same age: personAge is declared as static. Remove the static keyword in front of the declaration.
UPDATE: and yes, use getters and setters instead of accessing fields directly.
To summarise:
remove the static keyword in front of personAge declaration,
declare personAge and personName as private to ensure you use the getters and setters,
remove the extends Person in class PersonMain,
in method main, use the getters and the setters instead of accessing the fields directly.
UPDATE 2: Oh! yes! some more issues:
in the setters, assign the argument to the field, not the other way around (personName=name; and personAge=age).
variable i should go from 0 to 3 because the array is declared with a size of 4: for(int i=0;i<4;i++) or better: for(int i=0;i<ageStore.length;i++),
move the Scanner declaration and initialisation out of the loop, and use only one of them.
If you are collecting information that is required for later processing, you need to store all of that information.
At the moment, you are storing the ages in an array, but throwing away the names.
So, instead of keeping an age array like this:
static int [] ageStore=new int [4];
... try keeping an array of Persons. Plus you don't need to keep them outside the main method. So, in the main method:
Person[] persons = new Person[4];
Also, fix your Person class so that the age is not static and the variables are private:
private int personAge;
private String personName;
Now create a single scanner because you don't need one per loop or per input:
Scanner input= new Scanner(System.in);
Then create your loop, but run it from 0 to less than the length of the array to fill (because indexes in Java start at 0):
for (int i = 0; i < persons.length; i++) {
Then make a new Person object to populate:
Person person = new Person();
Then collect the name and age from the user (remembering that i is 1 less than what you want to show to the user):
System.out.println("Please enter name for person " + (i + 1) );
person.setName(input.next());
System.out.println("Now, input " + person.getName() + "'s age" );
person.setAge(input.nextInt());
And add the person to the array:
persons[i] = person;
Then you can close your loop.
So far you should have:
package person;
import java.util.Scanner;
public class PersonMain {
public static void main(String[] args) {
Person[] persons = new Person[4];
Scanner input= new Scanner(System.in);
for (int i = 0; i < persons.length; i++) {
Person person = new Person();
System.out.println("Please enter name for person " + (i + 1) );
person.setName(input.next());
System.out.println("Now, input " + person.getName() + "'s age" );
person.setAge(input.nextInt());
persons[i] = person;
}
// matching code will go here
}
}
Now we need to do the matching part.
One way of doing that is to check each item against all the items after it in the list. That would look like this:
for (int i = 0; i < persons.length - 1; i++) { // until 'persons.length - 1' because if we look at the last item, it has nothing left to compare against
Person currentPerson = persons[i];
for (int j = i + 1; j < persons.length; j++) { // start at the next index (i + 1)
if (currentPerson.getAge() == persons[j].getAge()) { // we have an age match
System.out.println(currentPerson.getName() + " has the same age as " + persons[j].getName());
}
}
}
I'm trying to create a program called Student Grades, which simulates a grade book for a class with 15 students who each have four test scores. I must use a two-dimensional array to store my data. I need to format my data like "Jeremy Folson, 85, 99, 33, 44". I am having trouble specifically with adding the different students to my array and displaying it properly. I understand that my adding function does not work because will add the same data 15 times. Can someone please explain how to make my code perform the desired task?
// Declare two-dimensional array
Object [][] grades = new Object [15][5];
private void btnAddActionPerformed(java.awt.event.ActionEvent
evt) {
//Clear output area
txtaDisplay.setText(null);
// Declare variables
String firstName, lastName, name;
int test1, test2, test3, test4;
firstName = txtFirstName.getText();
lastName = txtLastName.getText();
name = firstName + " " + lastName;
test1 = Integer.parseInt(txtTest1.getText());
test2 = Integer.parseInt(txtTest2.getText());
test3 = Integer.parseInt(txtTest3.getText());
test4 = Integer.parseInt(txtTest4.getText());
for(int i = 0; i < 15 ; i++){
grades[i][0] = name;
grades[i][1] = test1;
grades[i][2] = test2;
grades[i][3] = test3;
grades[i][4] = test4;
}
}
public void displayArray() {
StringBuilder sb = new StringBuilder();
for (int row = 0; row < 15; row++) {
for( int col=0; col < 5; col++) {
sb.append(String.valueOf(grades[row][col]));
sb.append(", ");
}
sb.append("\n");
}
txtaDisplay.append(sb.toString());
}
First, your data structure conststing only of Object should be improved. A first draft would be:
class StudentEntry
{
String name;
Integer[] grade = new Integer[4];
}
List<StudentEntry> gradBook = new ArrayList<>();
Your main question was why the same combination was entered 15 times. This is due to the aspect that you only read once the input to firstName, ... and then assigned it in the for-loop to every row.
As we don't see when btnAddActionPerformed is called two possibilities:
a. Called each time a student is entered: Just create a new StudentEntry and add it to the gradBook (or if you stay with arrays: keep a counter how many students have already been added, e.g. a static int).
b. Called only when all student records have been entered: use a for-loop and read the next student data inside the loop:
for (int i = 0; i < 15 ; i++) {
StudentEntry student = new StudentEntry();
student.name = txtFirstName.getText() + " " + txtLastName.getText();
...
studentBook.add(student);
}
Having a really hard time with this problem. I've tried searching to find a similar situation but I can't seem to find anything that helps. I feel like I've got it 99% of the way and it's probably something very simple but I can't for the life of me figure it out.
I have two classes. ClassA and Restaurant.
The problem is that in my method call for printRestaurant() in the main method of ClassA, some of the methods need to receive the array with restaurant names but when I use the methods, it reprompts for the restaurant names each time it hits the next method instead of only prompting once and then moving to execute the next method.
ClassA:
import java.util.Scanner;
public class ClassA
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String ownerName = "";
System.out.printf("%nWhat is the name of the owner?");
ownerName = input.nextLine();
Restaurant rest = new Restaurant(ownerName);
rest.arraySize();
rest.printRestaurant(ownerName,rest.setRestaurants(),rest.setCustomers(rest.setRestaurants()),rest.calcAvgDailyRev(rest.setRestaurants()));
input.close();
System.exit(0);
}//END main()
}//END Application Class ClassA
Restaurants:
public class Restaurant
{
//Fields
String ownerName = "";
int size = 0;
Scanner input = new Scanner(System.in);
public Restaurant()
{
}//END Restaurant()
public Restaurant(String name)
{
ownerName = name;
}//END Restaurant(String ownerName)
public void arraySize()
{
System.out.printf("%n%s, how many restaurants do you own? ",ownerName);
size = input.nextInt();
}//END arraySize()
public String[] setRestaurants()
{
String[] restNames = new String[size];
input.nextLine(); // clears buffer
for(int row = 0;row < restNames.length; row++)
{
System.out.printf("%nEnter restaurant %d",row+1);
restNames[row] = input.nextLine();
}//END for col < restNames.length
return restNames;
}//END setRestaurants()
public int[] setCustomers(String array[])
{
int[] noCustomers = new int[size];
for(int i = 0;i<noCustomers.length;i++)
{
System.out.printf("%nEnter the average number of daily customers for %s: ",array[i]);
noCustomers[i] = input.nextInt();
}//END for i < size
return noCustomers;
}//END setCustomers()
public double[] calcAvgDailyRev(String array[])
{
double[] avgBill = new double[size];
input.nextLine(); //Clears buffer
for(int i = 0;i<avgBill.length;i++)
{
System.out.printf("%nEnter the average bill for %s: ",array[i]);
avgBill[i] = input.nextDouble();
}//end for i < size
return avgBill;
}//END calcAvgDailyRev(String array)
public void printRestaurant(String name, String restName[], int customers[], double dailyAvg[])
{
System.out.printf("%n%n%S's RESTAURANTS",name);
for(int i=0;i<size;i++)
{
double avgRevenue = customers[i]*dailyAvg[i];
System.out.printf("%n%nRestaurant: %s"
+"%nAverage No of Daily Customers: %d"
+"%nAverage Bill Per Customer: $%,.2f"
+"%nAverage Daily Revenue: $%,.2f",restName[i],customers[i],dailyAvg[i],avgRevenue);
}//END for i < size
}//END printRestaurant()
}//END Restaurant
Here is an example of the desired output:
What is the name of the owner? Cliff
Cliff, how many restaurants do you own? 2
Enter restaurant 1: Eggs
Enter restaurant 2: Bacon
Enter the average number of daily customers for Eggs: 250
Enter the average number of daily customers for Bacon: 200
Enter the average bill per customer for Eggs: 12
Enter the average bill per customer for Bacon: 15
CLIFF’s RESTAURANT
Restaurant: Eggs
Average No of Daily Customers: 250
Average Bill per Customer: $12.00
Average Daily Revenue: $3,000.00
Restaurant: Bacon
Average No of Daily Customers: 200
Average Bill per Customer: $15.00
Average Daily Revenue: $3,000.00
If you need any additional information please let me know. Any help would be GREATLY appreciated.
You need the value returned by the method. But here you are calling the method, and as per the method definition is prompting for input.
So, instead of calling the method, again and again, you can save the return type and use whereever needed.
e.g.
String restName[] = rest.setRestaurants();
int numberOfCust[] = rest.setCustomers(restName);
double dailAvgRev[] = rest.calcAvgDailyRev(restName);
You can use theses values restName, numberOfCust,dailAvgRev to print Restaurant information.
I guess the problem is you don't have a while loop in your main method. So the nextLine() will get executed only once without going back to the scanning routine. You can also define a special string such as "quit" to indicate you want to quit the scanning process.
Try the following maybe? :D
import java.util.Scanner;
public class ClassA {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String ownerName = "";
System.out.printf("%nWhat is the name of the owner?");
while (!(ownerName = input.nextLine()).equals("quit")) {
Restaurant rest = new Restaurant(ownerName);
rest.arraySize();
...
}
input.close();
System.exit(0);
}//END main()
}//END Application Class ClassA
It will keep prompting until you enter the string "quit". Hope it helps.
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());
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