I'm trying to create an array of math students, science students, and computer students based on the user input.
So basically the user should choose what student they want to add and then enter the student details.
Below I have added the code I have so far:
Main Java class:
public class Lab4 {
public static final int DEBUG = 0;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Student s[] = new Student[10];
s[0] = new MathStudent(4,5);
s[1] = new MathStudent(5,7);
s[2] = new MathStudent(2,8);
s[3] = new MathStudent(3,6);
s[4] = new ScienceStudent(8,9);
s[5] = new ScienceStudent(3,6);
s[6] = new ScienceStudent(4,9);
s[7] = new ComputerStudent(6,12);
s[8] = new ComputerStudent(11,14);
s[9] = new ComputerStudent(13,17);
}
}
Student class:
public class Student {
private String name;
private int age;
public String gender = "na";
public static int instances = 0;
// Getters
public int getAge(){
return this.age;
}
public String getName(){
return this.name;
}
// Setters
public void setAge(int age){
this.age = age;
}
public void setName(String name){
if (Lab4.DEBUG > 3) System.out.println("In Student.setName. Name = "+ name);
this.name = name;
}
/**
* Default constructor. Populates name,age,gender,course and phone Number
* with defaults
*/
public Student(){
instances++;
this.age = 18;
this.name = "Not Set";
this.gender = "Not Set";
}
/**
* Constructor with parameters
* #param age integer
* #param name String with the name
*/
public Student(int age, String name){
this.age = age;
this.name = name;
}
/**
* Gender constructor
* #param gender
*/
public Student(String gender){
this(); // Must be the first line!
this.gender = gender;
}
/**
* Destructor
* #throws Throwable
*/
protected void finalize() throws Throwable{
//do finalization here
instances--;
super.finalize(); //not necessary if extending Object.
}
public String toString (){
return "Name: " + this.name + " Age: " + this.age + " Gender: "
+ this.gender;
}
public String getSubjects(){
return this.getSubjects();
}
}
MathStudent class:
public class MathStudent extends Student {
private float algebraGrade;
private float calculusGrade;
public MathStudent(float algebraGrade, float calculusGrade) {
this.algebraGrade = algebraGrade;
this.calculusGrade = calculusGrade;
}
public MathStudent() {
super();
algebraGrade = 6;
calculusGrade = 4;
}
// Getters
public void setAlgebraGrade(float algebraGrade){
this.algebraGrade = algebraGrade;
}
public void setCalculusGrade(float calculusGrade){
this.calculusGrade = calculusGrade;
}
// Setters
public float getAlgebraGrade() {
return this.algebraGrade;
}
public float getCalculusGrade() {
return this.calculusGrade;
}
/**
* Display information about the subject
* #return
*/
#Override
public String getSubjects(){
return("Algebra Grade: " + algebraGrade + " Calculus Grade: "
+ calculusGrade);
}
}
scienceStudent class:
public class ScienceStudent extends Student {
private float physicsGrade;
private float astronomyGrade;
/**
* Default constructor
*/
public ScienceStudent() {
super();
physicsGrade = 6;
astronomyGrade = 7;
}
public ScienceStudent(float physicsGrade, float astronomyGrade) {
this.physicsGrade = physicsGrade;
this.astronomyGrade = astronomyGrade;
}
// Getters
public void setPhysicsGrade(float physicsGrade){
this.physicsGrade = physicsGrade;
}
public void setAstronomyGrade(float astronomyGrade){
this.astronomyGrade = astronomyGrade;
}
// Setters
public float getPhysicsGrade() {
return this.physicsGrade;
}
public float getAstronomyGrade() {
return this.astronomyGrade;
}
/**
* Display information about the subject
* #return
*/
#Override
public String getSubjects(){
return("Physics Grade: " + physicsGrade + " Astronomy Grade: "
+ astronomyGrade);
}
}
computerStudent class:
public class ComputerStudent extends Student {
private float fortanGrade;
private float adaGrade;
/**
* Default constructor
*/
public ComputerStudent() {
super();
fortanGrade = 4;
adaGrade = 9;
}
public ComputerStudent(float fortanGrade, float adaGrade) {
this.fortanGrade = fortanGrade;
this.adaGrade = adaGrade;
}
// Getters
public void setFortanGrade(float fortanGrade){
this.fortanGrade = fortanGrade;
}
public void setAdaGrade(float adaGrade){
this.adaGrade = adaGrade;
}
// Setters
public float getFortanGrade() {
return this.fortanGrade;
}
public float getAdaGrade() {
return this.adaGrade;
}
/**
* Display information about the subject
* #return
*/
#Override
public String getSubjects(){
return("Fortan Grade: " + fortanGrade + " Ada Grade: " + adaGrade);
}
}
How Would I go about this?
You can ask for the number of students with type on each input and dynamically create the object.
Here is an example
System.out.println("Enter total number of students");
int n = scannerObject.nextInt();
Student students[] = new Students[n];
for(int i=0;i<n;i++){
int type = scannerObject.nextInt();
if(type == 1)
students[i] = new MathStudent();
}
Similarly, you can write for others.
For allowing user to enter his choice as input
You can do this(interpreted by your comments)
Pseudo code -
Print:
Enter 1 for math student
Enter 2 for Science student
Enter 3 for Comp student
Input choice
Now in your code use either multiple if else or better switch statement
switch(choice){
case 1: create object of math student
break;
case 2: create object of science student
break;
case 3:create object of comp student
break;
default: if not above by default do this
}
You could use an ArrayList and switch case to make your life easier. Your code should be like this:
import java.util.ArrayList;
import java.util.Scanner;
public class Students {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Student> students = new ArrayList<>();
int age;
boolean addMore = true;
String name, gender;
Student st;
while (addMore) {
System.out.print("Give lesson (Computers, Math, Science): ");
String lesson = input.nextLine();
switch (lesson) {
case "Math":
// Read student's info
System.out.print("Give student's name: ");
name = input.nextLine();
System.out.print("Give student's gender: ");
gender = input.nextLine();
System.out.print("Give student's age: ");
age = input.nextInt();
System.out.print("Give student's Algebra grade: ");
int alg = input.nextInt();
System.out.print("Give student's Calculus grade: ");
int calc = input.nextInt();
input.nextLine(); // This is needed in order to make the next input.nextLine() call work (See here: https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo )
// Create the student object and pass info
st = new MathStudent(alg, calc);
st.setName(name);
st.setAge(age);
st.gender = gender;
students.add(st); // Adding the student in the list
System.out.println(st);
System.out.println(((MathStudent) st).getSubjects());
break;
case "Science":
// Read student's info
System.out.print("Give student's name: ");
name = input.nextLine();
System.out.print("Give student's gender: ");
gender = input.nextLine();
System.out.print("Give student's age: ");
age = input.nextInt();
System.out.print("Give student's Physics grade: ");
int physics = input.nextInt();
System.out.print("Give student's Astronomy grade: ");
int astronomy = input.nextInt();
input.nextLine();// This is needed in order to make the next input.nextLine() call work (See here: https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo )
// Create the student object and pass info
st = new ScienceStudent(physics, astronomy);
st.setName(name);
st.setAge(age);
st.gender = gender;
students.add(st); // Adding the student in the list
System.out.println(st);
System.out.println(((ScienceStudent) st).getSubjects());
break;
case "Computers":
// Read student's info
System.out.print("Give student's name: ");
name = input.nextLine();
System.out.print("Give student's gender: ");
gender = input.nextLine();
System.out.print("Give student's age: ");
age = input.nextInt();
System.out.print("Give student's Fortran grade: ");
int fortran = input.nextInt();
System.out.print("Give student's Ada grade: ");
int ada = input.nextInt();
input.nextLine();// This is needed in order to make the next input.nextLine() call work (See here: https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo )
// Create the student object and pass info
st = new ComputerStudent(fortran, ada);
st.setName(name);
st.setAge(age);
st.gender = gender;
students.add(st); // Adding the student in the list
System.out.println(st);
System.out.println(((ComputerStudent) st).getSubjects());
break;
default:
System.out.println("Wrong lesson");
addMore = false;
break;
}
if (addMore) {
System.out.println("Add another student? (y/n)");
String ans = input.nextLine();
addMore = ans.equals("y");
} else {
addMore = true;
}
}
System.out.println("Students");
for (Student student : students) {
System.out.println(student);
}
}
}
The code above asks for the lesson name (Computers, Math, Science) and if it is one of them it reads all the info about the student and the grades for the corresponding lesson. It creates the objects and adds them in the list students. When all info is added, it asks the user if he/she wants to add another student and if he writes the letter y, then all these are made again, until the user answers something different than the letter y (the letter n in most cases). After these it prints all the students' info by itterating the list.
Note: I think in your code for the ComputerStudent class, you meant to name the variable fortranGrade and not fortanGrade (change it also in the getSubjects function).
Links:
Java ArrayList
Switch Case in Java
Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods
I hope this helped you. If you have any questions or wanted something more you can do it.
UPDATE
The code below does the same things, but it uses for loop instead of switch case, as you asked in your comment.
package students;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Lab4 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Student> students = new ArrayList<>();
int age;
boolean addMore = true;
String name, gender;
Student st;
ArrayList<Class<?>> studentClasses = new ArrayList<>();
studentClasses.add(MathStudent.class);
studentClasses.add(ComputerStudent.class);
studentClasses.add(ScienceStudent.class);
while (addMore) {
System.out.print("Give lesson (Computers, Math, Science): ");
String lesson = input.nextLine();
addMore = false;
for (Class studentClass : studentClasses) {
try {
st = (Student) studentClass.newInstance();
if (st.getLessonName().equals(lesson)) {
// Read student's info
System.out.print("Give student's name: ");
name = input.nextLine();
System.out.print("Give student's gender: ");
gender = input.nextLine();
System.out.print("Give student's age: ");
age = input.nextInt();
System.out.print("Give student's " + st.getSubjectsNames()[0] + " grade: ");
float firstSubj = input.nextFloat();
System.out.print("Give student's " + st.getSubjectsNames()[1] + " grade: ");
float secondSubj = input.nextFloat();
input.nextLine(); // This is needed in order to make the next input.nextLine() call work (See here: https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo )
// Create the student object and pass info
st = (Student) studentClass.getConstructor(float.class, float.class).newInstance(firstSubj, secondSubj);
st.setName(name);
st.setAge(age);
st.gender = gender;
students.add(st); // Adding the student in the list
System.out.println(st);
System.out.println(st.getSubjects());
addMore = true;
break;
}
} catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
Logger.getLogger(Lab4.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (addMore) {
System.out.println("Add another student? (y/n)");
String ans = input.nextLine();
addMore = ans.equals("y");
} else {
System.out.println("Wrong lesson. Try again.");
addMore = true;
}
}
System.out.println("Students");
for (Student student : students) {
System.out.println(student);
}
}
}
You also need to add the functions in the classes as mentioned bellow:
Student class:
public String getLessonName(){
return "";
}
public String[] getSubjectsNames(){
return new String[] {"", ""};
}
MathStudent class:
#Override
public String[] getSubjectsNames(){
return new String[] {"Algebra", "Calculus"};
}
#Override
public String getLessonName(){
return "Math";
}
ComputerStudent class:
#Override
public String[] getSubjectsNames(){
return new String[] {"Fortran", "Ada"};
}
#Override
public String getLessonName(){
return "Computers";
}
ScienceStudent class:
#Override
public String[] getSubjectsNames(){
return new String[] {"Physics", "Astronomy"};
}
#Override
public String getLessonName(){
return "Science";
}
Changes: The code firstly creates an arraylist with the student classes (studdentClasses) and adds all the classes for the students that are currently in the project (MathStudent, ComputerStudent, ScienceStudent). Then the user adds the lesson's name. Then (instead of the switch case) there is a for loop which itterates through the studdentClasses list and checks if the lesson's name that the user has written is the same with a student's class by using the getLessonName function. After that all the info for the student are asked and the grades for the subjects, and for the question (Give student's Physics grades) it uses the function getSubjectsNames. All the other things are like before.
You have a main class, that's what you need essentially, but you need to read from command line. Great, run from command line. Once you run, pay attention to what you did, you can pass parameters there as well. once you pass parameters, they go in line. This line is logically splitable, so split it within you code. for instance by pair of numbers after some key word like science and until next keyword and put again from java and ask a new question once you there.
Related
I have created a program in JAVA that has menu Options, 1 to 5. Option 4 being "Add student". Where it asks a 4 questions
Questions:
Please Enter student name:
Please Enter student course:
Please Enter student number:
Please Enter student gender:
After user has given these details, It will save into an array and ends the program. I am quite lost on how to save these details into an array.
This is my program where i tried to find a solution myself, But im relatively new to arrays and method myself.
public static void newstudent (String[] name,String[] course,int[] number,String[] gender)
{
}
public static void selection (int option) // Menu
{
switch (option)
{
case 1:
System.out.println("Display Student option");
break;
case 2:
System.out.println("Search Student");
break;
case 3:
System.out.println("Delete Student");
break;
case 4:
//code for adding new student
break;
case 5:
System.out.println("Exited");
break;
default:JOptionPane.showMessageDialog(null, "Invalid option! Please enter in the range from 1 to 5.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
public static void main(String[] args) {
//Start of Menu loop Statement
int option1 ;
do{
String option = JOptionPane.showInputDialog(null,"Enter your option:\n"+"\n"+"1. Display Students\n"+"2. Search Students\n" + "3. Delete Students\n"+"4. Add Students\n"+"5. Exit ","DMIT Students",JOptionPane.QUESTION_MESSAGE);
option1 = Integer.parseInt(option);
selection(option1);
}while(option1 <1 || option1 > 5);
// End of Menu Loop statement
}
}
i tried doing a for loop to add +1 to these array everytime a user inputs all these details but the for loop will be stuck in a infinite loop. Is there any suggestions that i can get? or easier solutions?
You shouldn't use arrays (the way you are using here) in the first place because you don't want to store the details of single student in four different places i.e. arrays. You can define a class Student with all the details you need and then it will be simple to add the details using class instances. Something like -
public class Student
{
private String m_name;
private int m_age;
private String m_course;
private String m_year;
private String m_section;
public Student( String name, int age, String course, String year, String section )
{
m_name = name;
m_age = age;
m_course = course;
m_year = year;
m_section = section;
}
public String getName()
{
return m_name;
}
public int getAge()
{
return m_age;
}
public String getCourse()
{
return m_course;
}
public String getYear()
{
return m_year;
}
public String getSection()
{
return m_section;
}
public String toString()
{
return "name: " + m_name + ", age: " + m_age +
", course: " + m_course + ", year: " + m_year +
", section: " + m_section;
}
public static void main(String[] args)
{
ArrayList<Student> students = new ArrayList<Student>();
Scanner input = new Scanner(System.in);
int menuChoice = 4;
do {
System.out.println("\t\t\tStudent Record Menu");
System.out.println("\t\t1. Add Student\t2. View Students\t3. Search Student\t4. Exit");
try {
System.out.println("Enter a choice: ");
menuChoice = Integer.parseInt(input.nextLine());
} catch (NumberFormatException e) {
continue;
}
if (menuChoice==1)
{
System.out.println("Full name:");
String name = input.nextLine();
int age = -1;
do {
try {
System.out.println("Age:");
age = Integer.parseInt(input.nextLine());
} catch (NumberFormatException e) {
System.out.println("Enter a number!");
continue;
}
} while (age <= 0);
System.out.println("Course:");
String course = input.nextLine();
System.out.println("Year:");
String year = input.nextLine();
System.out.println("Section:");
String section = input.nextLine();
Student student = new Student(name, age, course, year, section);
students.add(student);
} else if (menuChoice==2) {
System.out.println("Students:");
for (Student student : students)
{
System.out.println(student);
}
}
} while (menuChoice<4);
}
}
The above code snippet is referred from here.
I am a student and looking for help with an assignment. Here is the task: Create a CollegeCourse class. The class contains fields for the course ID (for example, “CIS 210”), credit hours (for example, 3), and a letter grade (for example, ‘A’).
Include get() and set()methods for each field. Create a Student class containing an ID number and an array of five CollegeCourse objects. Create a get() and set() method for the Student ID number. Also create a get() method that returns one of the Student’s CollegeCourses; the method takes an integer argument and returns the CollegeCourse in that position (0 through 4). Next, create a set() method that sets the value of one of the Student’s CollegeCourses; the method takes two arguments—a CollegeCourse and an integer representing the CollegeCourse’s position (0 through 4).
I am getting runtime errors on the second for loop where I am trying to get the data into the course array. It is asking for both the CourseID and Hours in the same line and regardless of what I respond with it I am getting an error, it almost seems like it is trying to get all the arrays variables at the same time. Here is my code which includes three classes. Any help to send me in the right direction is appreciated as I have spent a ton of time already researching to resolve.
public class CollegeCourse {
private String courseId;
private int creditHours;
private char grade;
public CollegeCourse(String id, int hours, char grade)
{
courseId=id;
creditHours = hours;
this.grade = grade;
}
public void setCourseId(String id)
{
courseId = id;//Assign course id to local variable
}
public String getCourseId()
{
return courseId;//Provide access to course id
}
public void setHours(int hours)
{
creditHours = hours;//Assign course id to local variable
}
public int getHours()
{
return creditHours;//Provide access to course id
}
public void setGrade(char grade)
{
this.grade = grade;//Assign course id to local variable
}
public char getGrade()
{
return grade;//Provide access to course id
}
}
Student Class
public class Student {
final int NUM_COURSES = 5;
private int studentId;
private CollegeCourse courseAdd;//Declares a course object
private CollegeCourse[] courses = new CollegeCourse[NUM_COURSES];
//constructor using user input
public Student(int studentId)
{
this.studentId=studentId;
}
public void setStudentId(int id)
{
studentId = id;//Assign course id to local variable
}
public int getStudentId()
{
return studentId;//Provide access to course id
}
public void setCourse(int index, CollegeCourse course)
{
courses[index] = course;
}
public CollegeCourse getCourse(int index)
{
return courses[index];
//do I need code to return the courseId hours, grade
}
}
InputGrades Class
import java.util.Scanner;
public class InputGrades {
public static void main(String[] args) {
final int NUM_STUDENTS = 2;
final int NUM_COURSES = 3;
Student[] students = new Student[NUM_STUDENTS];
int s;//subscript to display the students
int c;//subscript to display courses
int stId;
int csIndex;
String courseId = "";
int hours = 0;
//String gradeInput;
char grade = 'z';
CollegeCourse course = new CollegeCourse(courseId,hours, grade);//not sure if I am handling this correctly
Scanner input = new Scanner(System.in);
for(s = 0; s<NUM_STUDENTS; ++s)
{
students[s] = new Student(s);
System.out.print("Enter ID for student #" + (s+1) + ":");
stId = input.nextInt();
input.nextLine();
students[s].setStudentId(stId);
for(c=0; c < NUM_COURSES; ++c)
{
csIndex=c;
System.out.print("Enter course ID #" + (c+1) + ":");
courseId = input.nextLine();
course.setCourseId(courseId);
System.out.print("Enter hours:");
hours = input.nextInt();
input.nextLine();
course.setHours(hours);
String enteredGrade = "";
while(enteredGrade.length()!=1) {
System.out.print("Enter grade:");
enteredGrade = input.nextLine();
if(enteredGrade.length()==1) {
grade = enteredGrade.charAt(0);
} else {
System.out.println("Type only one character!");
}
}
course.setGrade(grade);
students[s].setCourse(csIndex, course);
}
}
for(s = 0; s<NUM_STUDENTS; ++s)
{
System.out.print("\nStudent# " +
students[s].getStudentId());
System.out.println();
for(c=0;c<NUM_COURSES;++c)
System.out.print(students[s].getCourse(c) + " ");
System.out.println();
}
}
}
After input.nextInt() you need to add one more input.nextLine(); and than you can read grade.
System.out.print("Enter hours:");
hours = input.nextInt();
input.nextLine();
course.setHours(hours);
Why it is needed? See this question: Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods
You should add a very simple length validation when you input the grade:
String enteredGrade = "";
while(enteredGrade.length()!=1) {
System.out.print("Enter grade:");
enteredGrade = input.nextLine();
if(enteredGrade.length()==1) {
grade = enteredGrade.charAt(0);
} else {
System.out.println("Type only one character!");
}
}
so the full main class code:
import java.util.Scanner;
/**
* Created by dkis on 2016.10.22..
*/
public class App {
public static void main(String[] args) {
final int NUM_STUDENTS = 10;
final int NUM_COURSES = 5;
Student[] students = new Student[NUM_STUDENTS];
//String name;
int s;//subscript to display the students
int c;//subscript to display courses
int stId;
int csIndex;
String courseId = "";
int hours = 0;
char grade = 'z';
CollegeCourse course = new CollegeCourse(courseId,hours, grade);//not sure if I am handling this correctly
Scanner input = new Scanner(System.in);
for(s = 0; s<NUM_STUDENTS; ++s)
{
students[s] = new Student(s);
System.out.print("Enter ID for student #" + s+1 + ":");
stId = input.nextInt();
input.nextLine();
students[s].setStudentId(stId);
for(c=0; c < NUM_COURSES; ++c)
{
//CollegeCourse course = students[s].getCourse(c);
csIndex=c;
System.out.print("Enter course ID#" + c+1 + ":");
courseId = input.nextLine();
course.setCourseId(courseId);
System.out.print("Enter hours:");
hours = input.nextInt();
input.nextLine();
course.setHours(hours);
String enteredGrade = "";
while(enteredGrade.length()!=1) {
System.out.print("Enter grade:");
enteredGrade = input.nextLine();
if(enteredGrade.length()==1) {
grade = enteredGrade.charAt(0);
} else {
System.out.println("Type only one character!");
}
}
course.setGrade(grade);
students[s].setCourse(csIndex, course);
}
}
for(s = 0; s<NUM_STUDENTS; ++s)
{
System.out.print("\nStudent# " +
students[s].getStudentId());
for(c=0;c<NUM_COURSES;++c)
System.out.print(students[s].getCourse(c) + " ");
System.out.println();
}
}
}
I am struggling to get this program to do exactly what the assignment asks. It throws a null pointer exception when trying to remove an added student. Also when I list the students, it shows null on everything.
-Code is fixed-
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Student> newStudents = new ArrayList<Student>();
System.out.println("Welcome to the Student Interface!.");
System.out.println("Please select a number from the options below \n");
while (true) {
// Give the user a list of their options
System.out.println("1: Add a student to the list.");
System.out.println("2: Remove a student from the list.");
System.out.println("3: Display all students in the list.");
System.out.println("0: Exit the student interface.");
// Get the user input
int userChoice = input.nextInt();
switch (userChoice) {
case 1:
addStudents(newStudents);
break;
case 2:
removeStudent(newStudents);
break;
case 3:
displayStudent(newStudents);
break;
case 0:
System.out.println("Thank you for using the student interface. See you again soon!");
System.exit(0);
}
}
}
public static void addStudents(ArrayList<Student> newStudents) {
Scanner input = new Scanner(System.in);
Student newStudent = new Student();
System.out.println("Please enter first name: ");
String First_Name = input.next();
newStudent.setFirst_Name(First_Name);
System.out.println("Please enter last name: ");
String Last_Name = input.next();
newStudent.setLast_Name(Last_Name);
System.out.println("Please enter major: ");
String Major = input.next();
newStudent.setMajor(Major);
System.out.println("Please enter GPA: ");
String GPA = input.next();
newStudent.setGPA(GPA);
System.out.println("Please enter UIN: ");
String UIN = input.next();
newStudent.setUIN(UIN);
System.out.println("Please enter NetID: ");
String NetID = input.next();
newStudent.setNetID(NetID);
System.out.println("Please enter Age: ");
String Age = input.next();
newStudent.setAge(Age);
System.out.println("Please enter Gender: ");
String Gender = input.next();
newStudent.setGender(Gender);
if (newStudents.size() <= 10) {
newStudents.add(newStudent);
System.out.println("Student added\n");
} else {
System.out.println("\n Student interface is full!");
}
}
private static void displayStudent(ArrayList<Student> newStudents) {
for (Student e : newStudents) {
System.out.println(e);
}
}
private static void removeStudent(ArrayList<Student> newStudents) {
Scanner input = new Scanner(System.in);
System.out.println("Please, enter the UIN to remove the Student: ");
String uin = input.nextLine();
for (Student e : newStudents) {
if (e.getUIN().equals(uin)) {
newStudents.remove(e);
System.out.println("Student removed");
break;
}
else {
System.out.println("Sorry, no such student with this " + uin + " " + "number exist");
}
}
}
Student Class:
package assignments;
public class Student{
private String First_Name;
private String Last_Name;
private String Major;
private String GPA;
private String UIN;
private String NetID;
private String Age;
private String Gender;
public String getFirstName()
{
return First_Name;
}
public void setFirst_Name(String value)
{
this.First_Name = value;
}
public String getLastName()
{
return Last_Name;
}
public void setLast_Name(String value)
{
Last_Name = value;
}
public String getMajor()
{
return Major;
}
public void setMajor(String value)
{
Major = value;
}
public String getGPA()
{
return GPA;
}
public void setGPA(String value)
{
GPA = value;
}
public String getUIN()
{
return UIN;
}
public void setUIN(String value)
{
UIN = value;
}
public String getNetID()
{
return NetID;
}
public void setNetID(String value)
{
NetID = value;
}
public String getAge()
{
return Age;
}
public void setAge(String value)
{
Age = value;
}
public String getGender()
{
return Gender;
}
public void setGender(String value)
{
Gender = value;
}
public String toString()
{
return "First Name: " + First_Name +
"\n Last Name: " + Last_Name +
"\n Major: " + Major +
"\n GPA: " +GPA+
"\n UIN: " + UIN +
"\n NetID: " + NetID+
"\n Age: " + Age+
"\n Gender: " + Gender;
}
public void createStudent(String first_Name2, String last_Name2, String major2, String gPA2, String uIN2, String netID2,
String age2, String gender2) {
first_Name2 = First_Name;
last_Name2 = Last_Name;
major2 = Major;
gPA2 = GPA;
uIN2 = UIN;
age2 = Age;
gender2 = Gender;
}
}
Your program runs about perfectly on my computer. Here’s an example run:
Welcome to the Student Interface!.
Please select a number from the options below
1: Add a student to the list.
2: Remove a student from the list.
3: Display all students in the list.
0: Exit the student interface.
2
Please, enter the UIN to remove the Student:
13
1: Add a student to the list.
2: Remove a student from the list.
3: Display all students in the list.
0: Exit the student interface.
1
Please enter first name:
o
Please enter last name:
v
Please enter major:
cs
Please enter GPA:
g
Please enter UIN:
79
Please enter NetID:
o
Please enter Age:
57
Please enter Gender:
m
Student added
1: Add a student to the list.
2: Remove a student from the list.
3: Display all students in the list.
0: Exit the student interface.
3
Student [firstName=o, lastName=v, major=cs, gPA=g, uIN=79, netID=o, age=57, gender=m]
1: Add a student to the list.
2: Remove a student from the list.
3: Display all students in the list.
0: Exit the student interface.
2
Please, enter the UIN to remove the Student:
79
Student removed
1: Add a student to the list.
2: Remove a student from the list.
3: Display all students in the list.
0: Exit the student interface.
3
1: Add a student to the list.
2: Remove a student from the list.
3: Display all students in the list.
0: Exit the student interface.
0
Thank you for using the student interface. See you again soon!
Potential issues in your program include: You have two Scanner objects on System.in, you may want to share just one. You don’t use the variable student_added. In my two cases the program didn’t report back to the user whether a student was removed or not. Your two TODO comments are obsolete and should be removed.
One of two reasons you'd get a NullPointerException on the remove operation. Either the ArrayList is null, or the object you are attempting to remove is null. Check for those.
The Cullerton Part District holds a mini-Olympics each summer. Create a class named Participant with fields for a name, age, and street address. Include a constructor that assigns parameter values to each field and a toString() method that returns a String containing all the values. Also include an equals() method that determines two Participants are equal if they have the same values in all three fields. Create an application with two arrays of at least 5 Participants each--one holds the Participants in the mini-marathon and the other holds Participants in the diving competition. Prompt the user for Participants who are in both events save the files as BC.java and ABC.java.
import javax.swing.JOptionPane;
import java.util.*;
public class ABC {
private static Participant mini[] = new Participant[2];
public static void main(String[] args) {
setParticipant();
displayDetail();
}
// BC p=new BC(name,age,add);
//displayDetails();
// System.out.println( p.toString());
public static void displayDetail() {
String name=null;
String add = null;
int age=0;
System.out.println("Name\tAdress\tAge");
BC p=new BC(name,age,add);
for (int x = 0; x < mini.length; x++) {
//Participant p1=mini[x];
System.out.println(p.toString());
}
}
public static String getName() {
Scanner sc = new Scanner(System.in);
String name;
System.out.print(" Participant name: ");
return name = sc.next();
}
// System.out.print(" Participant name: ");
// name = sc.next();
public static int getAge() {
int age;
System.out.print(" Enter age ");
Scanner sc=new Scanner(System.in);;
return age= sc.nextInt();
}
public static String getAdd() {
String add;
Scanner sc=new Scanner(System.in);;
System.out.print("Enter Address: ");
return add=sc.next();
}
public static void setParticipant(){
for (int x = 0; x < mini.length; x++) {
System.out.println("Enter loan details for customer " + (x + 1) + "...");
//Character loanType=getLoanType();
//String loanType=getLoanType();
String name=getName();
String add=getAdd();
int age=getAge();
System.out.println();
}
}
}
//another class
public class BC {
private String name;
private int age;
private String address;
public BC(String strName, int intAge, String strAddress) {
name = strName;
age = intAge;
address = strAddress;
}
#Override
public String toString() {
return "Participant [name=" + name + ", age=" + age + ", address=" + address + "]";
}
public boolean equals(Participant value){
boolean result;
if (name.equals(name) && age==value.age && address.equals(address))
result=true;
else
result=false;
return result;
}
}
outPut:
Enter loan details for customer 1...
Participant name: hddgg
Enter Address: 122
Enter age 12
Enter loan details for customer 2...
Participant name: ddjkjde
Enter Address: hdhhd23
Enter age 12
//Why I'm not getting right output
Name Adress Age
Participant [name=null, age=0, address=null]
Participant [name=null, age=0, address=null]
You are getting that output because of this method:
public static void displayDetail() {
String name=null;
String add = null;
int age=0;
System.out.println("Name\tAdress\tAge");
BC p=new BC(name,age,add);
for (int x = 0; x < mini.length; x++) {
//Participant p1=mini[x];
System.out.println(p.toString());
}
}
You are creating a BC with null for name and add and 0 for age. You are then printing it twice.
Here is my code. I did my work a bit off. I was supposed to not just do one applicant, I was supposed to do many and I was supposed to populate the applicants into 2 different arrays, one for graduates, and one for undergraduates. I need help figuring out how to make an empty array and fill up applicants in those. A start would help
import java.util.Scanner;
public class CollegeApplicant
{
String applicantName;
String collegeName;
public String getApplicantName()
{
return applicantName;
}
public void setApplicantName(String applicantName)
{
this.applicantName = applicantName;
}
public String getCollegeName()
{
return collegeName;
}
public void setCollegeName(String collegeName)
{
this.collegeName = collegeName;
}
public void checkCollege()
{
int choice;
Graduate g = new Graduate();
Undergraduate ug = new Undergraduate();
Scanner input = new Scanner(System.in);
System.out.println("1. Undergraduate");
System.out.println("2. Graduate");
System.out.println("enter your choice ");
choice = input.nextInt();
if (choice == 1)
{
System.out.println("Enter SAT marks :");
ug.SAT = input.nextDouble();
System.out.println("Enter GPA marks :");
ug.GPA = input.nextDouble();
}
else
{
System.out.println("Enter the origin of college:");
g.collegeOrigin = input.next();
System.out.println("Status :" + g.checkCollege());
}
}
public class Undergraduate
{
double SAT;
double GPA;
}
public class Graduate
{
String collegeOrigin;
String checkCollege()
{
String information = null;
if (collegeName.equals(collegeName)) information = "Applicant is applying from inside";
else information = "Applicant is applying from outside";
return information;
}
}
}
The Client
import java.util.Scanner;
public class CollegeApplicantClient extends CollegeApplicant
{
public static void main(String[] args)
{
TestCollege tc = new TestCollege();
Scanner input = new Scanner(System.in);
System.out.println("Enter the name of applicant ");
tc.setApplicantName(input.next());
System.out.println("enter the college name of applicant ");
tc.setCollegeName(input.next());
tc.checkCollege();
}
}
Here is an example of the possible output
Name: Joe
College Applied to: Harvard
SAT: 5
GPA: 2
Name: Tom
College Applied to: Yale
College of Origin: NYU – from outside
I need to be able to put the graduates in an array and the undergrads in an array. Then display it when it's all done