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]
Related
I have a simple project in java.
the project is a program for a teacher who wants to enter the grades for his students (three grades for each student) with five private attributes name,grade1, grade2, grade3and average and three methods: readGrades(), GetAverage() and getName(). I but them all but my problem is no matter what I did the output always gave me the average of the latest student I entered not the highest.I should also print his name not the average.
someone told me to use ArrayList but honestly I don't know how??
so if anyone can help me I'll appreciate it.
This is what i have so far
import java.util.Scanner;
class Student {
private String name;
private int grade1, grade2, grade3;
private double average;
void Setgrade1(int g1) {
grade1 = g1;
}
void Setgrade2(int g2) {
grade2 = g2;
}
void Setgrade3(int g3) {
grade3 = g3;
}
int Getgrade1() {
return grade1;
}
int Getgrade2() {
return grade2;
}
int Getgrade3() {
return grade3;
}
int readGrades() { //method that reads grades.
Scanner input = new Scanner(System.in);
int g1, g2, g3;
String name;
char choice;
do {
System.out.println(" --Please enter the student name: ");
name = input.next();
SetName(name);
System.out.println(" --Please enter the first grade: ");
g1 = input.nextInt();
Setgrade1(g1);
System.out.println(" --Please enter the the second grade: ");
g2 = input.nextInt();
Setgrade2(g2);
System.out.println(" --Please enter the the third grade: ");
g3 = input.nextInt();
Setgrade3(g3);
System.out.println(" Do you want to continue? enter the number ");
System.out.println(" 1- YES 2- NO ");
choice = input.next().charAt(0);
}
while (choice != '2');
return choice;
}
void SetAverage(double avr) {
average = avr;
}
double GetAverage() {
average = (grade1 + grade2 + grade3) / 3;
return average;
}
void SetName(String name1) {
name = name1;
}
String getName() {
return name;
}
}
public class TestStudent1 {
public static void main(String args[]) {
Student student = new Student();
student.readGrades();
student.GetAverage();
double i = 0;
double average = student.GetAverage();
if (i < average) {
i = average;
System.out.println("THE HIGHEST AVG :" + i);
}
}
}
A couple of problems in your code here are as follows:
1) It is giving you the output for the latest student is because you are modifying a single object all the time as your logic for entering more grades and name is inside the student itself which should be out.
2) To get the name and not the average you should call getName while printing.
3) To handle multiple students you can take out the logic of asking do you wish to continue in your main method and make an ArrayList of students in the main method to handle multiple student objects or you can do it with other collections as well like
List<Student> students = new ArrayList<>();
From here loop and add the student objects in the list using students.add(studentObj).
Then to get the highest compare the average of the students objects by using getAverage and find the student with the highest average from the list and print it.
That will do it. Try some of it and if you are stuck let us know.
I think your problem is you need to create multiple instances of student object in order to store the data of multiple students. What you did in your code is you will always replace your data with the last input. Here is an example of what you can do.
Student student1 = new Student();
Student student2 = new Student();
Student student3 = new Student();
You will also need a data structure to store all the instances of student object, you can either use Array or ArrayList. You will then add every instance of the student object into your data structure. After that, you can compare the average among all the students in your array.
First of all, remove user interaction method readGrades() from data holder Student class. It should be outside. I think that you should not hold average as separate field. This is not big dial to calculate it every time whey you invoke getAverage() method:
public final class Student {
private final String name;
private int grade1;
private int grade2;
private int grade3;
public Student(String name) {
this.name = name;
}
public void setGrade1(int grade1) {
this.grade1 = grade1;
}
public void setGrade2(int grade2) {
this.grade2 = grade2;
}
public void setGrade3(int grade3) {
this.grade3 = grade3;
}
public double getAverage() {
return (grade1 + grade2 + grade3) / 3.0;
}
public String getName() {
return name;
}
public int getGrade1() {
return grade1;
}
public int getGrade2() {
return grade2;
}
public int getGrade3() {
return grade3;
}
}
Second, do create separate method, that interacts with user (or probably other sources) to retrieved required number of students.
private static List<Student> getStudents() {
try (Scanner scan = new Scanner(System.in)) {
List<Student> students = new ArrayList<>();
char choice;
Student student;
do {
System.out.print(" --Please enter the student name: ");
students.add(student = new Student(scan.next()));
System.out.print(" --Please enter the first grade: ");
student.setGrade1(scan.nextInt());
System.out.print(" --Please enter the the second grade: ");
student.setGrade2(scan.nextInt());
System.out.print(" --Please enter the the third grade: ");
student.setGrade3(scan.nextInt());
System.out.println(" Do you want to continue? enter the number ");
System.out.println(" 1- YES 2- NO ");
choice = scan.next().charAt(0);
} while (choice != '2');
return students;
}
}
And finally very simple client's code:
List<Student> students = getStudents();
students.sort((s1, s2) -> Double.compare(s2.getAverage(), s1.getAverage()));
System.out.println("THE HIGHEST AVG :" + students.iterator().next().getName());
I'm providing an alternate approach that doesn't use List/ArrayList. Since this is homework, I won't provide code.
Since the requirement is to find the student with the highest average, and you're collecting each student and three grades at a time, you only need to keep track of two instances of Student at any one time. The one with the highest grade bestStudent, and the one being entered currentStudent.
After each student is entered, check to see whether currentStudent's average is higher than bestStudent's. If it is she's your new teacher's pet. Otherwise, discard. Keep in mind, you'll need to handle the first student a little bit differently.
You have only one instance object for that class, so, when you read data for more students, the next student will replace the data from the previous student.
In this case, to save all students and get information about all of them, is better use ArrayList, and push all new data to that list.
e.g:
List<Student> students = new ArrayList<>();
And in the end, you can get the average that you need.
Edit:
Code using ArrayList:
Student class
public class Student {
private String name;
private int grade1, grade2, grade3;
private double average;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getGrade1() {
return grade1;
}
public void setGrade1(int grade1) {
this.grade1 = grade1;
}
public int getGrade2() {
return grade2;
}
public void setGrade2(int grade2) {
this.grade2 = grade2;
}
public int getGrade3() {
return grade3;
}
public void setGrade3(int grade3) {
this.grade3 = grade3;
}
public double getAverage() {
return average;
}
public void setAverage(double average) {
this.average = average;
}
public double calculateAverage() {
return (grade1 + grade2 + grade3) / 3;
}
}
Main Class
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
public class MainStudent {
public static void main(String[] args) {
//Create a list of student
List<Student> studentList = new ArrayList<Student>();
Scanner input = new Scanner(System.in);
int g1, g2, g3;
String name;
int choice;
do {
//Instantite a new object student
Student student = new Student();
System.out.println(" --Please enter the student name: ");
name = input.next();
student.setName(name);
System.out.println(" --Please enter the first grade: ");
g1 = input.nextInt();
student.setGrade1(g1);
System.out.println(" --Please enter the the second grade: ");
g2 = input.nextInt();
student.setGrade2(g2);
System.out.println(" --Please enter the the third grade: ");
g3 = input.nextInt();
student.setGrade3(g3);
System.out.println(" Do you want to continue? enter the number ");
System.out.println(" 1- YES 2- NO ");
choice = input.nextInt();
student.setAverage(student.calculateAverage());
//Push a new object to student list
studentList.add(student);
}
while (choice != 2);
//Get student object with the higher average
Student higherStudent = Collections.max(studentList, Comparator.comparing(c -> c.getAverage()));
System.out.println("THE HIGHEST AVG :" + higherStudent.getAverage() + "\n BELONG'S TO: " + higherStudent.getName());
}
}
I have transfer the while code to main method, and create a new method to calculate the average, because the getAverage is how we will retrieve the value calculate.
Edit: Get higher average with simple loop
Replacing:
Student higherStudent = Collections.max(studentList, Comparator.comparing(c -> c.getAverage()));
By:
Student higherStudent = new Student();
for(int i = 0; i < studentList.size(); i++) {
if(i == 0) {
higherStudent = studentList.get(i);
} else if(higherStudent.getAverage() < studentList.get(i).getAverage()) {
higherStudent = studentList.get(i);
}
}
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.
Not actually sure what's wrong, just that at line 81 my scan object is skipped and then the program continues with no clear attempt to read anything, thoughts on what's wrong? btw working in eclipse
import java.util.*;
public class Hospital
{
//--- Instance Variables
private Patient patient;
private Scanner scan;
private double totalPrivateRoomCharges;
private double totalSemiPrivateRoomCharges;
private double totalWardRoomCharges;
private double totalTelephoneCharges;
private double totalTelevisionCharges;
private double totalReceipts;
//--- Constructors
public Hospital()
{
scan = new Scanner(System.in);
totalPrivateRoomCharges = 0;
totalSemiPrivateRoomCharges = 0;
totalWardRoomCharges = 0;
totalTelephoneCharges = 0;
totalTelevisionCharges = 0;
totalReceipts = 0;
mainMenu();
}
//--- Methods
public void mainMenu()
{
int ans = 0;
do
{
System.out.println(" Community Hospital");
System.out.println();
System.out.println(" Main Menu");
System.out.println();
System.out.println("1) Enter Patient Billing Information");
System.out.println("2) Print Daily Summary Report");
System.out.println("3) Exit");
System.out.println();
System.out.print("Selection: ");
ans = scan.nextInt();
System.out.println();
if(ans == 1)
{
patientBillingInfo();
}
if(ans == 2)
{
printSummaryReport();
}
}
while(ans != 3);
}
// precondition: none
// postcondition: displays a menu that allows the user to enter a patient's
// billing info which includes the patient's name, the number of days the
// patient stayed in the hospital, and the type of room
// (private, semi-private, ward).
// Once the patient info is retrieved a patient object is created and a
// billing report is generated that includes the patient's name, length
// of stay, and the charges incurred including the bill total.
// The totals that are used to print the hospitals daily summary report
// are updated.
public void patientBillingInfo()
{
String name = "";
int days = 0;
String room = "";
System.out.println(" Community Hospital");
System.out.println();
System.out.println(" Patient Billing Query");
System.out.println();
System.out.println("Enter Patient Name: ");
here the scan object seems to be completely skipped and dose not read at all just moves to the next line and continues.
name = scan.nextLine(); //getting skiped
System.out.println("Enter number of days in Hospital: ");
days = scan.nextInt();
System.out.println("Enter Room type(P, S, W): ");
room = scan.next();
System.out.println();
System.out.println();
if(!((room.equalsIgnoreCase("P")) || (room.equalsIgnoreCase("S")) || (room.equalsIgnoreCase("W"))))
{
System.out.println("Incorect room information");
System.out.println("Please enter P, S, or W for room selection");
System.out.println();
patientBillingInfo();
}
else
{
if(room.equalsIgnoreCase("P"))
totalPrivateRoomCharges += 1*days;
if(room.equalsIgnoreCase("S"))
totalSemiPrivateRoomCharges += 1*days;
if(room.equalsIgnoreCase("W"))
totalWardRoomCharges += 1*days;
totalTelephoneCharges += 1*days;
totalTelevisionCharges += 1*days;
patient = new Patient(name, days,room);
}
System.out.println(" Community Hospital");
System.out.println();
System.out.println(" Patient Billing Statement");
System.out.println();
System.out.println("Patient's name: " + patient.getName());
System.out.println("Number of days in Hospital: " + patient.getDays());
System.out.println();
System.out.println("Room charge $ " + patient.getRoomCharge());
System.out.println("Telephone charge $ " + patient.getTelephoneCharge());
System.out.println("Television charge $ " + patient.getTelevisionCharge());
System.out.println();
System.out.println("Total charge $ " +patient.getTotalCharge());
System.out.println();
System.out.println();
mainMenu();
}
// precondition: none
// postcondition: a summary report is printed that includes the daily total
// room charges for each type of room, the daily total telephone charges,
// and the daily total television charges. The report also includes the
// total receipts for the day.
public void printSummaryReport()
{
double tPRC = 225.0*totalPrivateRoomCharges;
double tSPRC = 165.0*totalSemiPrivateRoomCharges;
double tWRC = 95.0*totalWardRoomCharges;
double tTpC = 1.75*totalTelephoneCharges;
double tTvC = 3.50*totalTelevisionCharges;
double tR = tPRC+tSPRC+tWRC+tTpC+tTvC;
System.out.println(" Community Hospital");
System.out.println();
System.out.println(" Daily Billing Summary");
System.out.println();
System.out.println("Room Charges");
System.out.println(" Private: $" + tPRC);
System.out.println(" Semi-Private: $" + tSPRC);
System.out.println(" Ward: $" + tWRC);
System.out.println("Telephone Charges: $" + tTpC);
System.out.println("Telvision Charges: $" + tTvC);
System.out.println();
System.out.println("Total Receipts: $" + tR);
System.out.println();
}
}
edit: so it just occurred to me that maybe just maybe the rest of the code that this goes with might be useful dunno why I didn't think about this sooner but here's the rest
the class that actually runs
public class Administrator
{
public static void main(String[] args)
{
Hospital hospital = new Hospital();
}
}
and the class that works the patient info
public class Patient
{
//--- Constants
public final double PRIVATE = 225.00;
public final double SEMI = 165.00;
public final double WARD = 95.00;
public final double TELEPHONE = 1.75;
public final double TELEVISION = 3.50;
//--- Instance Variables
private String name;
private String roomType;
private int days;
//--- Constructors
public Patient(String n, int d, String rT)
{
name = n;
days = d;
roomType = rT;
}
//--- Methods
// precondition: none
// postcondition: returns the patient name
public String getName()
{
return name;
}
// precondition: none
// postcondition: returns the length of stay in days
public int getDays()
{
return days;
}
// precondition: none
// postcondition: returns the room type ("P", "S", "W")
public String getRoomType()
{
return roomType;
}
// precondition: none
// postcondition: returns the room charge which is dependant upon
// the room type and the length of stay.
public double getRoomCharge()
{
double charge = 0;
if(getRoomType().equalsIgnoreCase("P"))
charge = 225.00*getDays();
if(getRoomType().equalsIgnoreCase("S"))
charge = 165.00*getDays();
if(getRoomType().equalsIgnoreCase("W"))
charge = 95.00*getDays();
return charge;
}
// precondition: none
// postcondition: returns the telephone charge which is dependant upon
// the length of stay
public double getTelephoneCharge()
{
double charge = 1.75*getDays();
return charge;
}
// precondition: none
// postcondition: returns the television charge which is dependant upon
// the length of stay
public double getTelevisionCharge()
{
double charge = 3.50*getDays();
return charge;
}
// precondition: none
// postcondition: returns the total charge which is the sum
// of the room charge, telephone charge, and television charge.
public double getTotalCharge()
{
double charge = getRoomCharge()*getTelephoneCharge()+getTelevisionCharge();
return charge;
}
}
really don't know why it didn't occur to me sooner to do this but whatever live and lern right
You could simply scan a line and then parse it as the integer for Integer values.
so for reading integers instead of
val=scan.nextInt()
you could use
String strVal = scan.nextLine();
try {
val = Integer.parseInt(strVal);
} catch (NumberFormatException e) {
//maybe try again, or break the code ... or proceed as you wish.
}
this is because the nextInt() does not take the "Enter" key into account, and when you press enter after the nextInt() the int is read into the variable expecting nextInt() and the "Return" Key is accepted by the nextLine() which results in an empty line being read into the variable.
In public void mainMenu() you need to add scan.nextLine(); after ans = scan.nextInt(); in order to clear the rest of the input buffer.
ans = scan.nextInt();
scan.nextLine(); // <----- Add this line here
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.