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.
Related
Trying to update the fees in the ArrayList, once option 3 is selected, one is to input reg no then add fee for that specific student. Once the added fee has be keyed in, the added fee should be added to the initially set fee then update the total fee in the ArrayList. Please help.
When I run my code and add more than one student the initial fee I set for the last student I have entered gets updated yo all the students
Here is my code...
package schoolfinance;
import java.util.*;
public class Student
{
private final String m_name;
private final String m_regNo;
private final String m_course;
private final String m_year;
static double m_fees;
final double total_fees = 50000;
public Student(){
this("", "", "", "", 0.0);
}
public Student( String name, String regNo, String course, String year, double fees )
{
m_name = name;
m_regNo = regNo;
m_course = course;
m_year = year;
m_fees = fees;
}
public String getName()
{
return m_name;
}
public String getAge()
{
return m_regNo;
}
public String getCourse()
{
return m_course;
}
public String getYear()
{
return m_year;
}
public double getFees()
{
return m_fees;
}
public void setFees(Double fees)
{
Student.m_fees = fees;
}
/**
*
* #return
*/
#Override
public String toString()
{
double balance = total_fees - m_fees;
return "Name: " + m_name + ",\t Reg No: " + m_regNo +
",\t Course: " + m_course + ",\t Year: " + m_year +
",\t Fees Paid: " + m_fees + ",\t Balance: " + balance;
}
public static void main(String[] args)
{
ArrayList<Student> students = new ArrayList<>();
try (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. Add Fees\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();
System.out.println("Registration Number:");
String regNo = input.nextLine();
System.out.println("Course:");
String course = input.nextLine();
System.out.println("Year:");
String year = input.nextLine();
float fees = -1;
do {
try {
System.out.println("Fees Paid:");
fees = Integer.parseInt(input.nextLine());
} catch (NumberFormatException e) {
System.out.println("Enter a number!");
}
} while (fees <= 0);
Student student = new Student(name, regNo, course, year, fees);
students.add(student);
} else if (menuChoice==2) {
System.out.println("Students:");
for (Student student : students){
System.out.println(student);
}
} else if (menuChoice==3){
Scanner in = new Scanner(System.in);
System.out.println("Enter Student Registration Number: ");
String id = in.nextLine();
students.forEach((Student student) -> {
if(student.m_regNo.equals(id)){
System.out.println("Found it");
System.out.println(student);
Scanner new_fee = new Scanner(System.in);
System.out.println("Enter Added Fee: ");
double added_fee = new_fee.nextFloat();
double add_fee = added_fee + m_fees;
System.out.println(add_fee);
student.setFees(add_fee);
}
System.out.println("No Student Record Found Matching that Registration Number!!");
});
}else if (menuChoice < 1 || menuChoice > 4) {
System.out.println("Unrecognized Menu Choice, Please re-enter");
}
} while (menuChoice != 4);
}
}
}
When I run the code and choose option 1, it will prompt for details like full name, reg no, course, year and fee i.e
Full name: Billy Dan
Reg No: BIT100
Course: IT
Year: 3
Fee: 10,000
If I choose option 1 again and add details of another student, the fee value which I'll insert in the second student will be updated too for the first student which I don't want.
Now if option 3 is selected, you'll be prompted for reg no of a particular student you want to update his/her fee. If the reg no is found it will spit out details of that student and then prompt you enter your new fee. So I want when i enter the new fee, the program takes this new fee, adds it to the initial fee then save the total fee as the initial fee.
The program now works fine, though the last fee entered gets updated to the all the other students, for example if my first student had a fee of 5000 then I add another student and insert 7000 as his/her fee, the 7000 will override the 5000 of the first student, so they end up having the same fees
To update the values of your Student objects you need to give the class methods that allow you to do so. You currently only have getters to return the values like
public String getName()
{
return m_name;
}
What you need to do is add setters for those properties as well eG
public void setName(String name)
{
this.m_name = name;
}
Note that in order to be able to update the values of your fields you need to remove the final modifier from them!
As the final modifier indicates that a variable cannot be reassigned you need to decide whether to remove them and make the fields not final, or you need to accept the fact that the attributes of your Student class cannot be changed and work with that.
then you can use those setters in your code where you have already found the student object you want to modify:
System.out.println("Found it");
System.out.println(student);
student.setName("some new Name");
I m unable to figure out what are you trying to say but it is the simple examples how to update values in ArrayList in java
import java.util.ArrayList;
public class UpdateArrayListValues {
public static void main(String args[]) {
ArrayList<Integer> arraylist = new ArrayList<Integer>();
arraylist.add(1);
arraylist.add(2);
arraylist.add(3);
arraylist.add(4);
arraylist.add(5);
arraylist.add(6);
arraylist.add(7);
System.out.println("ArrayList before update: "+arraylist);
//Updating 1st element
arraylist.set(0, 11);
//Updating 2nd element
arraylist.set(1, 22);
//Updating 3rd element
arraylist.set(2, 33);
//Updating 4th element
arraylist.set(3, 44);
//Updating 5th element
arraylist.set(4, 55);
System.out.println("ArrayList after Update: "+arraylist);
}
}
Here is the output
ArrayList before update: [1, 2, 3, 4, 5, 6, 7]
ArrayList after Update: [11, 22, 33, 44, 55, 6, 7]
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'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.
im working on a school project.
We have to create a contact list.
So, i created a class generating objects like.
package coursework_q2;
public class Agenda {
private String name;
private long phoneNumber;
private String email;
private String type;
public Agenda(){
name = "";
phoneNumber = 0;
email = "";
type = "";
}//end of constructor
#Override
public String toString() {
return "\nName: " + this.getName() +
", Number: " + this.getPhoneNumber() +
", Email: " + this.getEmail() +
", Type: " + this.getType();
}
//setters
public void setName(String n){
name = n;
}//end of setName
public void setPhoneNumber(long n){
phoneNumber = n;
}//end of setPhoneNumber
public void setEmail(String e){
email = e;
}
public void setType(int t){
if (t==1){
type = "Personal";
}else{
type = "Business";
}
}//end of setType
//getters
public String getName(){
return name;
}//end of getName
public long getPhoneNumber(){
return phoneNumber;
}//end of getPhoneNumber
public String getEmail(){
return email;
}//end of getEmail
public String getType(){
return type;
}//end of getType
}//end of class
And in my other class i store them in an arraylist.
My problem is that i dont know how to create as many contacts as the user wants.
For example:
package testcourse;
import java.util.ArrayList;
import java.util.Scanner;
public class CourseWork_Q2 {
public static void main(String[] args) {
ArrayList<Agenda> contacts = new ArrayList();
Scanner in = new Scanner(System.in);
int check;
String contact;
String search;
Agenda a;
a = new Agenda();
int select=0;
int b=0;
do {
System.out.println("1. Add Contact\n2. Edit Contact\n3. Delete Contact\n4. Display All Contacts\n5. Quit");
System.out.print("Please use the numbers 1-5 to choose an option: ");
do{//input validation
check=0;
if(in.hasNextInt()){
select = in.nextInt();
if(1<=select && 5>=select){
check=1;
}else{
System.out.println("Invalid Input!\nPlease use the numbers 1-5 to choose an option: ");
System.out.println("1. Add Contact\n2. Edit Contact\n3. Delete Contact\n4. Display All Contacts\n5. Quit");
}//end of if
}else{
System.out.println("Invalid Input!\nPlease use the numbers 1-5 to choose an option: ");
System.out.println("1. Add Contact\n2. Edit Contact\n3. Delete Contact\n4. Display All Contacts\n5. Quit");
in.next();
}//end of if
}while(check==0);
switch(select){
case 1: System.out.println("Add Contact");
System.out.print("Please enter your contact name: ");
a.setName(in.next());
System.out.print("\nPlease enter your contact phone-number: ");
a.setPhoneNumber(in.nextLong());
System.out.print("\nPlease enter your contact email: ");
a.setEmail(in.next());
System.out.print("\nPlease choose your contact type: ");
System.out.println("\n1. Personal\n2. Business");
a.setType(in.nextInt());
contacts.add(a);
break;
case 2: System.out.println("Edit Contact");
System.out.println("Please enter the name of the contact you wish to edit: ");
search = in.next();
for(int i=0; i<contacts.size(); i++){
contact = (contacts.get(i)).toString();
if(contact.contains("Name: "+search)){
System.out.println(contacts.get(i));
System.out.println("Please edit the name");
a.setName(in.next());
}
}
break;
case 3: System.out.println("Delete Contact");
break;
case 4: System.out.println("Display All Contact");
for (int i=0; i<contacts.size(); i++){
System.out.println(contacts.get(i));
}
break;
case 5:
System.exit(5);
break;
}//end of switch
}while (!(check==5));
}//end of main
}//end of class
and so on..
How i can do this automatically with my code? So the user can create as many contacts as he wants?
Thank you!
Create an ArrayList of Agendas:
ArrayList<Agenda> contacts = new ArrayList<Agenda>();
Every time you want to add a contact, create a new Agenda, set the values, and add it to the ArrayList
Agenda a = new Agenda();
// Do stuff to the agenda/contact, like set names and stuff
contacts.add(a); // Adds the agenda/contact to the ArrayList
To edit a contact, all you need to do is retrieve it from the ArrayList with the index of it in the array.
int index = 1; // Set it to whichever you need
Agenda a = contacts.get(index);
// Now change whatever is in the agenda
To remove a contact, just remove it from the ArrayList using the index.
int index = 5;
contacts.remove(index);
I'm having a problem with a specific part of a program. What I want to do is iterate, search and display an element from an ArrayList.
So I tried implementing my own snippet to the main function of the code to try:
else if (menuChoice==3) {
System.out.println("Search Student:");
String search = input.nextLine();
for (Student student : students)
{
if (students.equals(search)){
System.out.println(student);
}
}
}
Hoping that it would iterate through the ArrayList and access/display that specific element in the list. It returns blank, what am I doing wrong?
Here's the whole code if you're wondering:
package student;
import java.util.*;
public class Student
{
private String r_name;
private int r_age;
private String r_course;
private String r_year;
private String r_section;
private String r_studno;
public Student( String name, int age, String course, String year, String section, String studno )
{
r_name = name;
r_age = age;
r_course = course;
r_year = year;
r_section = section;
r_studno = studno;
}
public String getName()
{
return r_name;
}
public int getAge()
{
return r_age;
}
public String getCourse()
{
return r_course;
}
public String getYear()
{
return r_year;
}
public String getSection()
{
return r_section;
}
public String getStudno()
{
return r_studno;
}
public String toString()
{
return "Name: " + r_name + ", Age: " + r_age +
", Course: " + r_course + ", Year: " + r_year +
", Section: " + r_section + ", Student Number: " + r_studno;
}
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("Add a Student");
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();
System.out.println("Student Number:");
String studno = input.next();
Student student = new Student(name, age, course, year, section, studno);
students.add(student);
} else if (menuChoice==2) {
System.out.println("Students:");
for (Student student : students)
{
System.out.println(student);
}
} else if (menuChoice==3) {
System.out.println("Search Student:");
String search = input.nextLine();
for (Student student : students)
{
if (students.equals(search)){
System.out.println(student);
}
}
}
} while (menuChoice<4);
}
}
You are checking if the ArrayList students is equal to the String search. The result can only be false. I guess, you are trying to do the following:
for (Student student : students)
{
if (student.getName().equals(search))
{
System.out.println(student);
break;//assuming student name are unique. remove if not
}
}
You must compare the search key with the key id of student for example if all names are unique then use
for (Student student : students)
{
if (student.getname().equals(search)){
System.out.println(student);
}
}
You are compairing the whole student object reference with the search key how it will compare it
if you want to display the whole content then you will have to make a method in which you will get all details using the id eg:
getStudentbyname( String studentname){
here comes the code to get all data
}
then in your for loop call the method and store in array
for (Student student : students)
{
if (student.getname().equals(search)){
Arraylist<String> studentarr = student.getStudentbyname(student.getname());
System.out.println(""+studentarr)
}
}