Infinte Objects in an Arraylist (Java) - java

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);

Related

Create a program that allows to receive multiples entry data, shows the data from the list

i was told to make a program like that, after input i can see the data
This is my code, please help i had search how to do it but i mostly only if the data is already known not by user input.
is it using an array or using for?
i search many time but i still dont find like mine
ive tried using array but i dont know how to get the array like, there is 3 user input in one array. mostly i found just using one user input
and sometime i get the error where the string cannot meet the int type
import java.util.Scanner;
public class Case7{
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
int choose=0;
String name ="";
String pos = "";
int age = 0;
do{
System.out.println("JOB VACANCY");
System.out.println("===========");
System.out.println("1. Insert new data");
System.out.println("2. List of staff");
System.out.println("3. Search staff");
System.out.println("4. Exit");
System.out.print("Choose: ");
choose = input.nextInt();
if (choose == 1)
{
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
do{
System.out.print("Input staff name: ");
name = input.nextLine();
}while(name.length() < 3 || name.length() > 20);
do{
System.out.print("Input staff position [Manager | Analyst | Programmer]: ");
pos=input.nextLine();
}while(!pos.equalsIgnoreCase("Manager") && !pos.equalsIgnoreCase("Analyst") && !pos.equalsIgnoreCase("Programmer"));
do{
System.out.print("Input staff age: ");
age=input.nextInt();
}while(age <= 17);
System.out.println("Data has been added!");
input.nextLine();
input.nextLine();
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
}
else if (choose == 2)
{
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
for (int i = 1; i < 6 ; i++ )
{
System.out.println("Staff ID :" + i);
System.out.println("==============");
System.out.println("1. name : " +name );
System.out.println("2. position : " +pos );
System.out.println("3. age : " +age );
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
}
}
Can I suggest a radically different implementation?
You can use a switch to score the options and You can use a LinkedList to store all the new staff member dinamically.
Here's my commented code:
static LinkedList<Staffer> staff=new LinkedList<>(); //ours database
static Scanner input = new Scanner (System.in);
public static void main(String[] args) {
String s="";
int number=-1;
while(number!=4){ //if your choice is 4, we can exit!
//Chooser:
System.out.print("JOB VACANCY\n===========\n1. Input data\n2. Show Data\n3.Delete Data\n4.£xit\nYour choice: ");
s=input.nextLine();
if(s.matches("\\d+")){ //Check if s is a number
number=Integer.parseInt(s);
switch(number){
case 1: input(); break;
case 2: showData(); break;
case 3: deleteData(); break;
case 4: System.out.println("Goodbye!"); break;
default: System.out.println("Number not valid. Try again!");
}
}else
System.out.println("Number not valid. Try again!");
}
}
private static void showData() {
for(Staffer st:staff)
System.out.println(st);
}
private static void deleteData(/*parameters*/) {
// You can delete a staffer by passing the name, for example
}
private static void input() {
//Plese, implements your data control options...
String name, position;
int age;
System.out.print("Name: ");
name=input.nextLine();
System.out.print("Position: ");
position=input.nextLine();
System.out.print("Age: ");
age=(Integer.parseInt(input.nextLine()));
Staffer staffer=new Staffer(name,position, age);
staff.add(staffer);
}
public static class Staffer{ //a staff member has 3 parameter: name, position and age... You can add others
/*You should store the name using only upperCase or LowerCase, or
* John Williams != john williams != JOHN WILLIAMS and you can have three times
* the same people.
*
* The position can be converted in enum for the same reason.
*/
private String name, position;
private int age;
public Staffer(String name, String position, int age){
this.name=name;
this.position=position;
this.age=age;
}
#Override
public String toString(){
return "Mr. "+name+", "+position+" (age: "+age+")";
}
}
You can see the following example output:
.
Obviously, you have to improve the output and all the data check options.

Saving an undefined number of user input

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.

Method to Find ArrayList Index to Where the Object Will be Added

I have an ArrayList that is being filled with customer information using a Customer class. In my addCustomerRecord method, I am calling findAddIndex within the addCustomerRecord method so the data entered will be sorted prior to displaying the data. Here is my code and do not mind the fileWhatever method, I don't use it.
public class CustomerDemo
{
//arrayList of customer objects
public static ArrayList<Customer> customerAL = new ArrayList<>();
public static void main (String[] args)
{
//to hold menu choice
String menuChoice = "";
Scanner kb = new Scanner(System.in);
System.out.println("To add a record press 'A': \n"
+ "to display all records press 'D': \n"
+ "to exit press 'Q': \n");
//loop priming read
menuChoice = kb.nextLine();
//make input case insensitive
menuChoice = menuChoice.toLowerCase();
do
{
if(menuChoice.equals("a"))
addCustomerRecord(kb);
else if(menuChoice.equals("d"))
{
displayCustomerRecords();
}
else if(menuChoice.equals("q"))
{
System.out.println("Program exiting..");
System.exit(0);
}
else
{
System.out.println("incorrect entry. Please re-enter a valid entry: \n");
menuChoice = kb.nextLine();
menuChoice = menuChoice.toLowerCase();
}
System.out.println("To add a record press 'A': \n"
+ "to display all records press 'D': \n"
+ "to exit press 'Q': \n");
menuChoice = kb.nextLine();
menuChoice = menuChoice.toLowerCase();
}while(menuChoice.equals("a") || menuChoice.equals("d") || menuChoice.equals("q"));
kb.close();
}
/* public static void displayCustomerRecords()
{
System.out.println();
for (int i = 0; i < customerAL.size(); ++i)
{
System.out.printf("%-15s", customerAL.get(i).getLastName());
System.out.printf("%-15s", customerAL.get(i).getFirstName());
System.out.printf("%-6s", customerAL.get(i).getCustID());
System.out.printf("%15s\n", customerAL.get(i).getPhoneNumber());
}
System.out.println();
}
/**
* prompts to enter customer data and mutator methods called
* with a Scanner object passed as an argument to set data
* #param location index position of where the element will be added.
* #param kb a Scanner object to accept input
*/
public static void addCustomerRecord(Scanner kb)
{
Customer currentCustomerMemoryAddress = new Customer();
System.out.println("Enter first name: \n");
String fName = kb.nextLine();
currentCustomerMemoryAddress.setFirstName(fName);
System.out.println("Enter last name: \n");
String lName = kb.nextLine();
currentCustomerMemoryAddress.setLastName(lName);
System.out.println("Enter customer phone number: \n");
String pNum = kb.nextLine();
currentCustomerMemoryAddress.setPhoneNumber(pNum);
System.out.println("Enter customer ID number: \n");
String ID = kb.nextLine();
currentCustomerMemoryAddress.setCustID(ID);
int addLocation = findAddLocation(currentCustomerMemoryAddress);
customerAL.add(addLocation, currentCustomerMemoryAddress);
currentCustomerMemoryAddress = null;
}
public static int findAddLocation(Customer cust)
{
int location = 0;
if(!customerAL.isEmpty())
{
for(int i = 0; i < customerAL.size(); i++)
{
//Stumped here
}
}
else
return location;
return location;
}
}
It looks like you are reinventing the wheel here William
Replace your code for displayCustomerRecords with this:
public static void displayCustomerRecords()
{
System.out.println();
customerAL.stream().map(c -> String.format("%-15s%-15s%-6s%15s\n",
c.getLastName(), c.getFirstName(), c.getCustID(), c.getPhoneNumber()))
.sorted()
.forEach(System.out::print);
System.out.println();
}
Update
Taking into account your comment you can replace your findAddLocationmethod by the following:
private static Comparator<Customer> comparator = Comparator.comparing(Customer::getLastName)
.thenComparing(Customer::getFirstName)
.thenComparing(Customer::getCustID)
.thenComparing(Customer::getPhoneNumber);
public static int findAddLocation(Customer cust)
{
int location = 0;
if(!customerAL.isEmpty())
{
for(Customer customerInList : customerAL)
{
if(comparator.compare(customerInList, cust) > 0) {
break;
}
location++;
}
}
return location;
}
We are traversing the array using Java's enhanced for-loop and comparing the objects using a Java 8 declared comparator (which I believe is the key to this assignment).
It would be a good idea if you could look into the Comparable interface and implement it in your Customer class. That way you could simply do a simple call to customerInList.compareTo(cust) to compare both objects.
As already stated, this is not a good practice and shouldn't be used in production code.

Creating an array of students based on user input

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.

Error when removing student from Java arraylist

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.

Categories

Resources