Thanks to some online assistance from the wonderful stackoverflow users, here is the edits to the enroll and drop student methods to add to the Student array set up. Now it's just on to get the other methods to work as well. Any insight for those would be helpful, especially for speed and efficiency at those points.
import java.util.Scanner;
public class School {
private Student[] theStudents;
public School() {
this.theStudents = new Student[] { null };// needs to start out as empty
}
/*
* next two methods would allow a user to add or drop a student into the
* student array for the school Also with Enroll student, should be able to
* assign a class to the student, i.e. Calculas, history, etc
*/
public void enrollStudent(Student newStudent) {
Student newStudents[] = new Student[theStudents.length+1];
for (int i = 0; i < theStudents.length; i++)
{
newStudents[i] = theStudents[i];
}
newStudents[theStudents.length] = newStudent;
theStudents = newStudents;
}
public void dropStudent(Student dropStudent) {
Student newStudents[] = new Student[theStudents.length-1];
for (int i = 0; i > theStudents.length; i--)
{
newStudents[i] = theStudents[i];
}
newStudents[theStudents.length] = dropStudent;
}
// add Test Score for a student
public double addTestScore(String newStudent, double testScore) {
testScores[posi] = testScore;
}
/*
* count the number of students in a given class, not the school
*/
public int countClassSize(String course) {
}
// get average average score of a given class
public double averageAverageScore(String course) {
}
/*
* add a programming language to only CS students at the school Will need to
* use the instanceof for proper type casting
*/
public String addProgrammingLanguage(String studentName, String programLanguage) {
}
/*
* Count the number of students in the school that know a certain
* programming language, again will need to typecast properly
*/
public int numberThatKnowLanguage(String programLanguage) {
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
String dropStudent, course;
System.out.println("Welcome to the School. Please select " + "Option 1 to enroll a regular student, \n "
+ "Option 2 to enroll a CompSci student, \n" + "Option 3 to drop a student, \n"
+ "Option 4 to add test score or programming language, or \n" + "Option 5 to perform class analytics.");
int Operation = input.nextInt();
/*
* Simple UI to add and drop students, will need to set the operation to
* call the add and drop students to fit them to the Student body array
* will need to make these two options loop until the user is satisfied
* with the size of the student body
*/
if (Operation == 1) {
System.out.println("Enter the # of regular students that you want to add to the school.");
int addStudents = input.nextInt();
/*
* Possibly create some type of input array to
* make it easier to enter the students' names
*/
System.out.println("Please enter the name and course of the student you are enrolling:");
Student newRegularStudent = (String) input.next();
course = input.next();
}
else if (Operation == 2) {
System.out.println("Enter the # of CompSci students that you want to add to the school.");
int addStudents = input.nextInt();
/*
* Possibly create some type of input array to make it easier to
* enter the students' names
*/
System.out.println("Please enter the name and course of the student you are enrolling:");
Student newCompSciStudent = (String) input.next();
course = input.next();
}
else if (Operation == 3) {
System.out.println("Enter the # of students that you want to drop from the school.");
int dropStudents = input.nextInt();
/*
* Possibly create some type of input array to make
* it easier to enter the students' names
*/
System.out.println("Please enter the name of the student you wish to drop from the school:");
dropStudent = (String) input.next();
/*
* After the first two operations, will need to build to the UI to
* call the other five methods, will need to make it into a
* while/for loop so user can continue to add information as needed.
*/
}
else if (Operation == 4) {
System.out.println("Enter the # for what you want to add to a student's records."
+ "Enter 1 to enter a test score\n " + "Enter 2 to enter a programming language, enter 2.");
int optionNum1 = input.nextInt();
/*
* Possibly create some type of input array
* to make it easier to enter the students' names
*/
if (optionNum1 == 1) {
} else if (optionNum1 == 2) {
}
}
else if (Operation == 5) {
System.out.println("This is the analytics section of this program.\n");
System.out.println("Enter the # for which of the following analytics options that you want performed: "
+ "Enter 1 to count the # of students for a particular class,\n "
+ "Enter 2 to calculate the average average score for all students take a particular course, or\n "
+ "Enter 3 to count the # of CompSciStudents.");
int optionNum2 = input.nextInt();
if (optionNum2 == 1) {
System.out.println("Enter the course name that you want to know the # of students for.");
course = input.next();
Student classSize;
classSize.countClassSize(course);
}
else if (optionNum2 == 2) {
System.out.println("Enter the course name that you want \n"
+ "to calculate the average average test value for.");
course = input.next();
Student testAvg;
testAvg.averageAverageScore(course);
}
else if (optionNum2 == 3) {
System.out.println("Count the # of CompSciStudents who know a \n"
+ "particular programming language by entering that language name now.");
String programLanguage = input.next();
CompSciStudent csStudent;
csStudent.knowsLanguage(programLanguage);
}
}
input.close();
}
}
I don't know if this is the best way, but if I were you, I would just create a new array one size larger or smaller and fill it will the values from the old array each time you add or remove a value. For example:
public void enrollStudent(Student newStudent) {
Students newStudents[] = new Student[theStudents.length+1];
for (int i = 0; i < theStudents.length; i++)
{
newStudents[i] = theStudents[i];
}
newStudents[theStudents.length] = newStudent;
theStudents = newStudents;
}
Not very efficient but hey, it doesn't sound like you're doing anything that needs to be super efficient.
Related
The question asks "The number of fuel tanks can only be (2,4,8,10, 15,20)" this is aNbrTanks in the code below. I been trying to use an array to have these inputs. But then I get the error of Object cant be converted to int or int[] to int. I need to ask for input by JOptionPane and then ask again if it doesn't meet the standards.
package project2;
import javax.swing.JOptionPane;
/**
*
* #author Administrator
*/
public class VehicleApp {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
//name
String firstName = JOptionPane.showInputDialog("Please enter your first name");
while(firstName.equals("")){
firstName =JOptionPane.showInputDialog("Please enter a valid first name");
}
String lastName = JOptionPane.showInputDialog("Please enter your last name");
while(lastName.equals("")){
lastName =JOptionPane.showInputDialog("Please enter a valid first name");
}
String aName = firstName + " " + lastName;
//phone
String aphone = JOptionPane.showInputDialog("Please enter your number");
while(aphone.length()!=10){
aphone = JOptionPane.showInputDialog("Please enter a valid phone number");
}
String aPhone = ("" + aphone).replaceAll("(...)(...)(....)", "$1-$2-$3");
//vechicle number
int aNbrVehicles = Integer.parseInt(JOptionPane.showInputDialog("Enter the number of Vehicles"));
while(aNbrVehicles < 1 || aNbrVehicles > 10 ){
aNbrVehicles = Integer.parseInt(JOptionPane.showInputDialog("valid number of Vehicles"));
}
//fuel tank
int aNbrTanks = Integer.parseInt(JOptionPane.showInputDialog("Enter the number of Tanks"));
VehicleFactory JarApp = new VehicleFactory(aName, aPhone, aNbrVehicles, aNbrTanks);
JarApp.calcManufacturingCost();
JarApp.calcFuelTankCost();
JarApp.calcSubtotal();
JarApp.calcTax();
JarApp.calcTotal();
JOptionPane.showMessageDialog(null, JarApp.getSummary());
}
}
I just need ideas or help figuring out how to get an array or a statement that be used as int aNbrTanks like the question asks.
You could request values in a loop, as you suggest anyway.
My example shows the loop you can use. There are more efficient ways to test for the allowed values.
int aNbrTanks = 0;
while (true) {
try {
aNbrTanks = Integer.parseInt(JOptionPane.showInputDialog("Enter the number of Tanks"));the number of Vehicles"));
} catch (NumberFormatException e) {
e.printStackTrace(e);
}
if (aNbrTanks==2) {
break;
}
}
Coming back to your title question, you can use JOptionPane with an Object[], not int[]. It will then convert your list of choices into a JComboBox. Here is an example:
public static void main(String[] args) {
Object[] choices = new Object[]{2,3,5,8};
System.out.println(Arrays.toString(choices));
Object choice = JOptionPane.showInputDialog(null, "Enter the number of Tanks", "Tanks", JOptionPane.PLAIN_MESSAGE, null, choices, 2);
System.out.println(choice);
}
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 1 year ago.
Improve this question
I'm working on my final project for class where we are making a class to store employees, ID#, and salary ranges, then create methods and arrays that add to the class. So far, I have it set up to add new employees, and print all employees, but I am kind of confused how to get these two prompts:
Retrieve specific employee’s data - prompts user for the employee id and displays the corresponding employee’s data: id, name, and salary
Retrieve employees with salaries based on range - prompts user for the lowest and highest salary and displays all employees with salaries in that range. Display each employee on separate line with all information - name, id, and salary
How would I incorporate that into this following code?
import java.util.ArrayList;
import java.util.Scanner;
public class FP {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<EmployeeData> companyData = new ArrayList<>();
// Boolean loop and while loop to restart the program in all cases but 3
boolean loopAgain = true;
while (loopAgain) {
System.out.println("Main Menu:");
System.out.println("1: Load New Employee Data");
System.out.println("2: Print Employee Data");
System.out.println("3: Exit");
int answer = in.nextInt();
switch (answer) {
// Case 1 to be called on when user selects "1"
case 1: {
System.out.println("Load New Employee Data:");
System.out.println("Please enter the number of new Employees to be added to
the sytem.");
System.out.println();
int loop = in.nextInt();
//For loop to add the number to class EmployeeData
for (int i =0; i < loop; i++) {
companyData.add(new EmployeeData());
}
} break;
// Case 2 to be called on when user selects "2"
case 2: {
// for loop to display the employees information after being entered by the user
for (EmployeeData x : companyData) {
x.printData();
}
} break;
// Case 2 to be called on when user selects "3" breaking the loop and ending the program
case 3: loopAgain = false; break;
}
}
}
}
// Class to store information for user input of employee data
class EmployeeData {
// String variable for names
String name;
// Int variables for ID and Salary
int id, salary;
public EmployeeData() {
// scan options and prompts for user input to be stored in class Employee Data
Scanner in = new Scanner(System.in);
System.out.println();
System.out.println("Enter Employee Name: ");
System.out.println();
String name = in.nextLine();
System.out.println();
System.out.println("Enter Employee ID:");
System.out.println();
int id = in.nextInt();
System.out.println();
System.out.println("Enter Employee Salary: ");
System.out.println();
int salary = in.nextInt();
// callable and modified variables stored for case 2
this.name = name;
this.id = id;
this.salary = salary;
}
// print section to be shown to user when case 2 is selected
public void printData() {
System.out.println();
System.out.println("Employee: " + this.name);
System.out.println();
System.out.println("ID: " + this.id);
System.out.println();
System.out.println("Salary: " + this.salary);
System.out.println();
}
}
For case 4:
System.out.println("Please enter the id.");
System.out.println();
int id = in.nextInt();
boolean find = false;
for (EmployeeData employeeData : companyData) {
if (employeeData.id == id) {
find = true;
// todo print info
break;
}
}
if (!find) {
// todo print something
}
For case 5:
System.out.println("Please enter the min salary.");
System.out.println();
int min = in.nextInt();
System.out.println("Please enter the max salary.");
System.out.println();
int max = in.nextInt();
for (EmployeeData employeeData : companyData) {
if (employeeData.salary <= max && employeeData.salary >= min) {
// todo print info on one line
}
}
In addition, it is not a good practice to do scan operate in constructor when you load data, move it outside:
case 1:
for (int i =0; i < loop; i++) {
EmployeeData employeeData = new EmployeeData();
// todo scan and set value
companyData.add(employeeData);
}
And to make the program more complete, you should make some extra checks, such as that the ID cannot be repeated when load data.
So I have this program that builds a School using dynamic arrays instead of using Array List. I have the methods created and tested, everything works except I'm trying to get the UI to work.
The UI is supposed to take user input to build the array of Students. Normal students versus CS students. The problem is, when I enter in how many students I want to enter into the school either regular or CS students, it stops after I enter in the amount of students I request to enroll.
I want the ability to say enroll 5 students, then go back and be asked if I want to enroll more, drop a student, or do any of the other options listed on the main menu. That's my problem. Every time I try to add in a for loop or switch the if/else if statements around compilation errors abound. This is the entire code that I have created:
import java.util.Arrays;
import java.util.Scanner;
public class School {
private Student[] theStudents;
public School() {
this.theStudents = new Student[0];// needs to start out as empty
}
/*
* next two methods would allow a user to add or drop a student into the
* student array for the school ??Also with Enroll student, should be able
* to assign a class to the student, i.e. Calculas, history, etc??
*/
public void enrollStudent(Student newStudent) {
Student totalStudents[] = new Student[theStudents.length + 1];
for (int i = 0; i < theStudents.length; i++) {
totalStudents[i] = theStudents[i];
}
totalStudents[theStudents.length] = newStudent;
theStudents = totalStudents;
}
public void dropStudent(String dropStudent) {
boolean checkForName = false;
for (int i = 0; i < theStudents.length; i++) {
if (theStudents[i].getName().equals(dropStudent)) {
theStudents[i] = null;
checkForName = true;
}
}
if (checkForName == true) {
Student totalStudents[] = new Student[theStudents.length - 1];
for (int i = 0; i < totalStudents.length; i++) {
if (theStudents[i] == null) {
totalStudents[i] = theStudents[theStudents.length - 1];
} else {
totalStudents[i] = theStudents[i];
}
}
theStudents = totalStudents;
}
if (checkForName == false) {
System.out.println("The Student does not exist in the school");
}
}
// add Test Score for a student
public void addTestScore(String newStudent, double testScore) {
for (int i = 0; i < theStudents.length; i++) {
if (newStudent.equals(theStudents[i])) {
theStudents[i].addTestScore(testScore);
}
}
}
/*
* count the number of students in a given class, not the school
*/
public int countClassSize(String course) {
// Need to access how the course names are stored for the school to
// count this size.
int count = 0;
for (int i = 0; i < theStudents.length; i++) {
if (theStudents[i].getClassName().equals(course)) {
count = count + 1;
}
}
return count;
}
/*
* get average average score of the student array The student array is made
* up of Regular students and CompSciStudents. The average should take the
* average of both the average score for Students and average score of
* CompSciStudents and return the average average.
*/
public double averageAverageScore(String course) {
double avgAvgTest = 0;
for (int i = 0; i < theStudents.length; i++) {
if (theStudents[i].getClassName().equals(course)) {
avgAvgTest += theStudents[i].getTestAvg();
}
}
return avgAvgTest / this.countClassSize(course);
}
/*
* add a programming language to only CS students at the school Will need to
* use the instanceof for proper type casting
*/
public void addProgrammingLanguage(String studentName, String programLanguage) {
for (int i = 0; i < theStudents.length; i++) {
if (this.theStudents[i] instanceof CompSciStudent) {
CompSciStudent tempStudent = (CompSciStudent) this.theStudents[i];
tempStudent.learnedLanguage(programLanguage);
}
}
}
/*
* Count the number of students in the school that know a certain
* programming language, again will need to typecast properly
*/
public int numberThatKnowLanguage(String programLanguage) {
int count = 0;
for (int i = 0; i < theStudents.length; i++) {
if (this.theStudents[i] instanceof CompSciStudent) {
CompSciStudent tempStudent = (CompSciStudent) this.theStudents[i];
String knowThisLanguage = programLanguage;
tempStudent.learnedLanguage(knowThisLanguage);
count += 1;
}
}
return count;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
String dropStudent, course;
System.out.println("Welcome to the School. Please select\n" + " Option 1 to enroll a regular student,"
+ "Option 2 to enroll a CompSci student, \n" + "Option 3 to drop a student, \n"
+ "Option 4 to add test score or programming language, or \n" + "Option 5 to perform class analytics.");
int Operation = input.nextInt();
/*
* Simple UI to add and drop students, will need to set the operation to
* call the add and drop students to fit them to the Student body array
* will need to make these two options loop until the user is satisfied
* with the size of the student body
*/
if (Operation == 1) {
System.out.println("Enter the # of regular students that you want to add to the school.");
int addStudents = input.nextInt();
// Possibly create some type of input array to
// make it easier to enter the students' names. for(<type> <var
// name> : <array name>)
System.out.println("Please enter the name and course of the student you are enrolling:");
for (int i = 0; i < addStudents; i++) {
String newRegularStudent = (String) input.next();
course = input.next();
System.out.println("Enter next student's name and then the course's name that he is enrolling in.");
}
} else if (Operation == 2) {
System.out.println("Enter the # of CompSci students that you want to add to the school.");
int addStudents = input.nextInt();
/*
* Possibly create some type of input array to make it easier to
* enter the students' names
*/
System.out.println("Please enter the name and course of the student you are enrolling:");
String newCompSciStudent = (String) input.next();
course = input.next();
}
else if (Operation == 3) {
System.out.println("Enter the # of students that you want to drop from the school.");
int dropStudents = input.nextInt();
/*
* Possibly create some type of input array to make it easier to
* enter the students' names
*/
System.out.println("Please enter the name of the student you wish to drop from the school:");
dropStudent = (String) input.next();
/*
* After the first two operations, will need to build to the UI to
* call the other five methods, will need to make it into a
* while/for loop so user can continue to add information as needed.
*/
}
else if (Operation == 4) {
System.out.println("Enter the # for what you want to add to a student's records."
+ "Enter 1 to enter a test score\n " + "Enter 2 to enter a programming language, enter 2.");
int optionNum1 = input.nextInt();
/*
* Possibly create some type of input array to make it easier to
* enter the students' names
*/
if (optionNum1 == 1) {
} else if (optionNum1 == 2) {
}
}
else if (Operation == 5) {
System.out.println("This is the analytics section of this program.\n");
System.out.println("Enter the # for which of the following analytics options that you want performed: "
+ "Enter 1 to count the # of students for a particular class,\n "
+ "Enter 2 to calculate the average average score for all students take a particular course, or\n "
+ "Enter 3 to count the # of CompSciStudents.");
int optionNum2 = input.nextInt();
if (optionNum2 == 1) {
System.out.println("Enter the course name that you\n" + " want to know the # of students for.");
course = input.next();
Student classSize;
}
else if (optionNum2 == 2) {
System.out.println(
"Enter the course name that you want to \n" + "calculate the average average test value for.");
course = input.next();
Student testAvg;
}
else if (optionNum2 == 3) {
System.out.println("Count the # of CompSciStudents who know a particular programming\n"
+ " language by entering that language name now.");
String programLanguage = input.next();
CompSciStudent csStudent = null;
csStudent.knowsLanguage(programLanguage);
}
}
input.close();
}
}
You cannot change the size of an array in Java at runtime. The size of your array therefore will always be zero since you wrote:
this.theStudents = new Student[0];
I would suggest you to use:
ArrayLists<type> list = new ArrayLists<type>();
If you do now know how to use ArrayLists you can follow this tutorial.
Main Class;
package finalapp;
import java.util.Scanner;
/**
*
* #author bassammetwally
*/
public class FinalApp {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner input = new Scanner(System.in);
Team tem = new Team();
Tournament tour = new Tournament();
System.out.print("Whats the tournament name?\n");
tour.setTourName(input.next());
System.out.print("Please enter the tournamen date\n");
tour.setTourDate(input.next());
System.out.print("Please enter the location\n");
tour.setLocation(input.next());
System.out.print("Please enter number of Software Stations\n");
tour.setAvaliableHardwareIns(input.nextInt());
System.out.print("Please enter number of Hardware Stations\n");
tour.setAvaliableHardwareIns(input.nextInt());
System.out.print("Please enter number of field testing");
tour.setAvaliableFieldTesting(input.nextInt());
System.out.print("Please enter max number of teams\n");
tour.setMaxNumberOfTeams(input.nextInt());
tour.tourStatSet(1);
while (true)
{
int choice;
choice = input.nextInt();
if (choice == 1)
{
System.out.printf("Enter Team %s Names\n",tour.getMaxNumberOfTeams());
for (int i = 0; i >= tour.getMaxNumberOfTeams();i++)
{
System.out.print("Please Enter Team Name");
tour.addingTeam(input.next());
tem.teamStats(1);
tem.teamJudgeStat(1);
Have a PREPARING team turn the robot on
(set the robot status to READY) to prepare for inspections
}
}
else if ( choice == 2)
{
System.out.print("Sending prepareing teams");
//for (int a = 0; a >= tour.getTeamsChecked(); a++)
{
}
}
}
}
Question:
I'm making a robot contest simulation, and I'm trying to get the main class to:
Add teams, which I already did
Change status of each team in the array
But my main idea was to go through the ArrayList and change the variables in the other classes, but I couldn't figure out how to do it.
Is there any easier way to do this?
From what it sounds like you should be able to use simple getters and setters to do what you want.
Simply have a method that sets the value you want into an array, and another that gets the array or a specific index in the array. This way you can set and share the array between classes.
I've been tasked to create a practice database for a programming assignment.
It consists of asking the user for the data of a Course such as: the Instructor name, the section number, and the room number.
Then I ask the user for information about a student: the student's name, his gpa, his major, and his hours.
After getting the information for the Course, I must create an ArrayList of the Student class, and allow the user to input multiple students. So a basic prompt would go as such:
Please enter the section number (1 to 15)
5
Please enter the instructor for this section
Frankie
Please enter the room number.
A1230
Please enter a name. Press enter to quit
Tyler
Please enter a major
Frank
Please enter a grade point average
3.34
Please enter the hours
13
Please enter a name. Press enter to quit
5 Frankie A1230
Tyler 13 3.34 Frank
The sentinel to exit the loop asking for student information exits once the user inputs enter into the name prompt, then the information is printed below.
My problem is when the user tries to add more than one student into the ArrayList. Here's an example of what happens:
Please enter the section number (1 to 15)
4
Please enter the instructor for this section
Jimmie
Please enter the room number.
B1230
Please enter a name. Press enter to quit
Adam
Please enter a major
ITSD
Please enter a grade point average
3.45
Please enter the hours
5
Please enter a name. Press enter to quit
Tonny
Please enter a major
Business
Please enter a grade point average
3.64
Please enter the hours
13
Please enter a name. Press enter to quit
4 Jimmie B1230
Tonny 13 3.64 Business
Tonny 13 3.64 Business
The correct output should be:
Tonny 13 3.64 Business
Adam 5 3.45 ITSD
It seems that when I add the student inputs into my ArrayList, the previous values of the inputs are overwritten with the new values the user enters for the next Student. I'm thinking that there's something wrong with my toString() method in my Student class. Here are my three classes: I have a Driver (Tester), Student (validates inputs for student info), and Course (validates inputs for course info and returns a toString which is printed in the Driver main method).
Driver Class
- Holds the main method, asks the user to input information for the prompts, it then adds the inputs for the Student information into the getAdd method in the Course method
import java.util.Scanner;
public class Driver
{
Student stud = new Student();
Course cour2 = new Course();
public static void main(String[] args)
{
Driver driv = new Driver();
driv.getCourseInfo();
boolean another;
do
{
another = driv.getStudentInfo();
}while(another);
System.out.println(driv.cour2.toString());
}
public void getCourseInfo()
{
int sectionValid = 0;
int instructorValid = 0;
int roomValid = 0;
Scanner input = new Scanner(System.in);
System.out.println("Please enter the section number (1 to 15)");
sectionValid = cour2.setSectionNumber(input.nextInt());
while(!(sectionValid == 1))
{
System.out.println("Your input was invalid. Please enter the section number (1 to 15)");
sectionValid = cour2.setSectionNumber(input.nextInt());
}
input.nextLine();
System.out.println("Please enter the instructor for this section");
instructorValid = cour2.setInstructor(input.nextLine());
while (instructorValid == 0)
{
System.out.println("Your input cannot be blank. Please enter an instructor.");
instructorValid = cour2.setInstructor(input.nextLine());
}
System.out.println("Please enter the room number.");
roomValid = cour2.setRoom(input.nextLine());
while (roomValid == 0)
{
System.out.println("The room number cannot be blank. Please enter a room number.");
roomValid = cour2.setRoom(input.nextLine());
}
}
public boolean getStudentInfo()
{
boolean another = true;
int nameValid = 0;
int majorValid = 0;
int gradePointAverageValid = 0;
int hoursValid = 0;
Scanner input = new Scanner(System.in);
System.out.println("Please enter a name. Press enter to quit");
nameValid = stud.setName(input.nextLine());
if (nameValid == 1)
{
another = true;
System.out.println("Please enter a major");
majorValid = stud.setMajor(input.nextLine());
while (majorValid == 0)
{
System.out.println("The major cannot be blank. Please enter a major");
majorValid = stud.setMajor(input.nextLine());
}
System.out.println("Please enter a grade point average");
gradePointAverageValid = stud.setGradePointAverage(input.nextDouble());
while (gradePointAverageValid == 0)
{
System.out.println("The grade point average has to be between 0.00 and 4.00. Please enter a grade point average");
gradePointAverageValid = stud.setGradePointAverage(input.nextDouble());
}
System.out.println("Please enter the hours");
hoursValid = stud.setHours(input.nextInt());
while (hoursValid == 0)
{
System.out.println("Hours cannot be greater than 17. Please enter the hours");
hoursValid = stud.setHours(input.nextInt());
}
cour2.addStudent(stud);
}
else
{
another = false;
}
return another;
}
}
The Student Class: Holds validations for the inputs for student information and has a toString() method that returns the sectionNumber, room, etc. variables. This toString() is then called in the Course class to be printed for each instance of the ArrayList students. I believe this to be the area where I have a problem (toString())
import java.util.ArrayList;
public class Course
{
private int sectionNumber;
private String instructor;
private String room;
private ArrayList<Student> students = new ArrayList<Student>();
Student studs = new Student();
public int getSectionNumber()
{
return sectionNumber;
}
public int setSectionNumber(int sectionNumber)
{
int sectionValid = 0;
if (sectionNumber >= 1 && sectionNumber <= 15)
{
this.sectionNumber = sectionNumber;
sectionValid = 1;
}
return sectionValid;
}
public String getInstructor()
{
return instructor;
}
public int setInstructor(String instructor)
{
int instructorValid = 0;
if (instructor.length() != 0)
{
this.instructor = instructor;
instructorValid = 1;
}
return instructorValid;
}
public String getRoom()
{
return room;
}
public int setRoom(String room)
{
int roomValid = 0;
if (room.length() != 0)
{
this.room = room;
roomValid = 1;
}
return roomValid;
}
public void addStudent(Student stud)
{
students.add(stud);
}
public String toString()
{
String results = " ";
for (Student s : students)
{
results += "\n" + s.toString();
}
return this.sectionNumber + "\t" + this.instructor + "\t" + this.room + results;
}
}
And now finally, The Course Class: This holds similar properties to the Student class, it contains validations for the user inputs for the Course information, but it contains the ArrayList students variable (which is causing me problems). The toString() method within this class is called from the driver class, so this toString() method is the one being printed back to the user. I believe I correctly use the forreach loop to add the student inputs to a String, and then return that string to be printed. I believe this might be wrong too.. But I'm not too sure.
import java.util.ArrayList;
public class Course
{
private int sectionNumber;
private String instructor;
private String room;
private ArrayList<Student> students = new ArrayList<Student>();
Student studs = new Student();
public int getSectionNumber()
{
return sectionNumber;
}
public int setSectionNumber(int sectionNumber)
{
int sectionValid = 0;
if (sectionNumber >= 1 && sectionNumber <= 15)
{
this.sectionNumber = sectionNumber;
sectionValid = 1;
}
return sectionValid;
}
public String getInstructor()
{
return instructor;
}
public int setInstructor(String instructor)
{
int instructorValid = 0;
if (instructor.length() != 0)
{
this.instructor = instructor;
instructorValid = 1;
}
return instructorValid;
}
public String getRoom()
{
return room;
}
public int setRoom(String room)
{
int roomValid = 0;
if (room.length() != 0)
{
this.room = room;
roomValid = 1;
}
return roomValid;
}
public void addStudent(Student stud)
{
students.add(stud);
}
public String toString()
{
String results = " ";
for (Student s : students)
{
results += "\n" + s.toString();
}
return this.sectionNumber + "\t" + this.instructor + "\t" + this.room + results;
}
}
Sorry for the overload of information, I just wanted to present the full scope of the problem to so you all could see what was happening to everything. I'm still a novice in java programming, but I'm trying my best to learn. Any tips or advice is appreciated! This is already past due, so my grade has already suffered, I'd honestly just like to learn what I'm doing wrong.
Thanks! Please comment if you have any question regarding the scope, I tried to explain the problem well and show you a sample output.
To summarize:
I don't understand why my ArrayList is printing the final student information entered, rather than printing each individual student information (if that makes sense).
Please note: I have validated that this program does run and print out inputs, so if you try to copy and paste it into your own eclipse and there are errors, it might be from a copy-paste error that I've made from my own code, or some other compiler specific jargon.
I've not studied the code in detail but I only see one place you are creating a new Student. If you create one Student object then repeatedly set and reset the values inside that then it will give you the symptoms you are describing.
Note that you can add the same object multiple times to one list.
You haven't copied the students class... But the solution is:
The Problem is not that the ArrayList prints false. The problem is that you use the objects wrong...
You should create new objects of Student if you create a new student. And also create new object of course. If you just change the variables in one class you override your first input...
just add this to getCourseInfo: cour2 = new Course(); and this to getStudentInfo: stud = new Student();
Code:
import java.util.Scanner;
public class Driver
{
Student stud = new Student();
Course cour2 = new Course();
public static void main(String[] args)
{
Driver driv = new Driver();
driv.getCourseInfo();
boolean another;
do
{
another = driv.getStudentInfo();
}while(another);
System.out.println(driv.cour2.toString());
}
public void getCourseInfo()
{
int sectionValid = 0;
int instructorValid = 0;
int roomValid = 0;
cour2 = new Course();
Scanner input = new Scanner(System.in);
System.out.println("Please enter the section number (1 to 15)");
sectionValid = cour2.setSectionNumber(input.nextInt());
while(!(sectionValid == 1))
{
System.out.println("Your input was invalid. Please enter the section number (1 to 15)");
sectionValid = cour2.setSectionNumber(input.nextInt());
}
input.nextLine();
System.out.println("Please enter the instructor for this section");
instructorValid = cour2.setInstructor(input.nextLine());
while (instructorValid == 0)
{
System.out.println("Your input cannot be blank. Please enter an instructor.");
instructorValid = cour2.setInstructor(input.nextLine());
}
System.out.println("Please enter the room number.");
roomValid = cour2.setRoom(input.nextLine());
while (roomValid == 0)
{
System.out.println("The room number cannot be blank. Please enter a room number.");
roomValid = cour2.setRoom(input.nextLine());
}
}
public boolean getStudentInfo()
{
boolean another = true;
int nameValid = 0;
int majorValid = 0;
int gradePointAverageValid = 0;
int hoursValid = 0;
stud = new Student();
Scanner input = new Scanner(System.in);
System.out.println("Please enter a name. Press enter to quit");
nameValid = stud.setName(input.nextLine());
if (nameValid == 1)
{
another = true;
System.out.println("Please enter a major");
majorValid = stud.setMajor(input.nextLine());
while (majorValid == 0)
{
System.out.println("The major cannot be blank. Please enter a major");
majorValid = stud.setMajor(input.nextLine());
}
System.out.println("Please enter a grade point average");
gradePointAverageValid = stud.setGradePointAverage(input.nextDouble());
while (gradePointAverageValid == 0)
{
System.out.println("The grade point average has to be between 0.00 and 4.00. Please enter a grade point average");
gradePointAverageValid = stud.setGradePointAverage(input.nextDouble());
}
System.out.println("Please enter the hours");
hoursValid = stud.setHours(input.nextInt());
while (hoursValid == 0)
{
System.out.println("Hours cannot be greater than 17. Please enter the hours");
hoursValid = stud.setHours(input.nextInt());
}
cour2.addStudent(stud);
}
else
{
another = false;
}
return another;
}
}
I will leave a clue.
Change your getStudentInfo() method to return populated Student object.
Similairly getCourseInfo() should return populated Course object.