import java.util.*;
import java.io.*;
public class Patient
{
private String patientId;
private String patientName;
private String gender;
private int age;
private String patientWardNumber;
private int patientBedNumber;
private String dateRegistered;
private String treatment;
private int wardedDuration;
private double price;
private double payment;
public Patient()
{
String patientId =" ";
String patientName =" ";
String patientWardNumber =" ";
String dateRegistered =" ";
String treatment =" ";
int patienBedDuration = 0;
int wardedDuration = 0;
int age = 0;
String gender = " ";
double price = 0.00;
}
public Patient(String ID,String N,String G,int A,String WN,int BN,String DR,String T,int WD)
{
patientId = ID;
patientName = N;
gender = G;
age = A;
patientWardNumber = WN;
patientBedNumber = BN;
dateRegistered = DR;
treatment = T;
wardedDuration = WD;
}
public void SetPatient(String ID,String N,String G,int A,String WN,int BN,String DR,String T,int WD)
{
patientId = ID;
patientName = N;
gender = G;
age = A;
patientWardNumber = WN;
patientBedNumber = BN;
dateRegistered = DR;
treatment = T;
wardedDuration = WD;
}
public String getPatientId()
{
return patientId;
}
public String getPatientName()
{
return patientName;
}
public String getGender()
{
return gender;
}
public int getAge()
{
return age;
}
public String getPatientWardNumber()
{
return patientWardNumber;
}
public int getPatientBedNumber()
{
return patientBedNumber;
}
public String getDateRegistered()
{
return dateRegistered;
}
public String getTreatment()
{
return treatment;
}
public int getWardedDuration()
{
return wardedDuration;
}
public double getPrice()
{
return price;
}
public double getPayment()
{
return payment;
}
public String toString()
{
return patientId+" "+patientName+" "+gender+" "+age+" "+patientWardNumber+" "+patientBedNumber+" "+dateRegistered+" "+treatment+" "+wardedDuration+" "+price+" "+payment;
}
public static void main(String[]args)
{
ArrayList PatientList = new ArrayList();
Scanner scan = new Scanner(System.in);
System.out.println("Enter how many patient are : ");
int num = scan.nextInt();
for(int i=0; i<num; i++)
{
System.out.println("Enter patient ID: ");
String patientId = scan.next();
System.out.println("Enter patient Name: ");
String patientName = scan.next();
System.out.println("Enter the patient's gender: ");
String gender = scan.next();
System.out.println("Enter the patient's age: ");
int age = scan.nextInt();
System.out.println("Enter patient ward number: ");
String patientWardNumber = scan.next();
System.out.println("Enter patient's Bed Number: ");
int patientBedNumber = scan.nextInt();
System.out.println("Enter patient's registeration date: ");
String dateRegistered = scan.next();
System.out.println("Enter the treatment: ");
String treatment = scan.next();
System.out.println("Enter the ward duration: ");
int wardedDuration = scan.nextInt();
Patient data = new Patient(patientId,patientName,gender,age,patientWardNumber,patientBedNumber,dateRegistered,treatment,wardedDuration);
PatientList.add(data);
}
System.out.println("Total patients are: "+PatientList.size());
System.out.println("Enter patient name : ");
Patient D= null;
Object data ;
String user=scan.next();
boolean found=false;
while(!PatientList.isEmpty())
{
if(D.getPatientName().equalsIgnoreCase(user))
{
found=true;
System.out.println(D.toString());
}
else if (found==false)
{
System.out.println("Patient is not found ! TRY AGAIN");
}
}
}
}
I got 2 problems while running this coding.First i cannot enter value for my ward duration. .Second,when i want to search my patient,it cannot display the information about the patient.Its say null pointer exception.i'm still beginner at java.someone can show me the solution?
This is my output
Because you haven't initialized your Patient object D inside the main() method.
Patient D= null;
and invoking a method on it.
if(D.getPatientName().equalsIgnoreCase(user)){ // Here D is null
found=true;
System.out.println(D.toString());
}
You have to create an object of Patient and initialized variable D like,
Patient D= new Patient();
For your "ward duration" input problem; you are reading strings with Scanner.next(). Note that this only reads one word. So if you were to enter "Level 1" for, e.g., treatment, only "Level" would be read; the "1" would be left on the stream and could corrupt later input (in your case, the "1" is being read by the nextInt() call for ward duration).
I suggest using Scanner.nextLine() for those string inputs instead. That way it will read every word on the full line, and will allow you to enter data that contains spaces without issue.
As for your NullPointerException, Kugathasan Abimaran's answer covers that well.
Also, you have another smaller issue. In your Patient constructor, you are not actually initializing any of the member fields. You are declaring and initializing local variables instead:
public Patient() {
String patientId = " ";
String patientName = " ";
String patientWardNumber = " ";
String dateRegistered = " ";
String treatment = " ";
int patienBedDuration = 0;
int wardedDuration = 0;
int age = 0;
String gender = " ";
double price = 0.00;
}
Should be:
public Patient() {
patientId = " ";
patientName = " ";
patientWardNumber = " ";
dateRegistered = " ";
treatment = " ";
patientBedNumber = 0; // <- note: "patienBedDuration" was probably a typo
wardedDuration = 0;
age = 0;
gender = " ";
price = 0.00;
}
By the way, traditionally "" is used to represent an empty string, not " ". Also, it's redundant to initialize the numeric fields to 0 because that's their default initial value anyways.
Related
I am trying to utilize the toString() in a class I have called Employee(). I have a 1D array of type Employee, which stores Employee Data, which include the Employee ID, Employee Name, Employee Address, and Employee Hire Date. I want the user to specify the amount of employees, and then enter the relevant data for however many employees the user wants. I then want to print the result for the user with the information entered. I keep getting some results that are null. I tried using an If statement that printed output if it didn't equal null, but that didn't work. I know the output works if I print out a single variable, such as address, but I want all variables to print out. Thank you for any help.
public class Address
{
public String address;
public void getAddress(String a)
{
address = a;
}
public String toString()
{
return address;
}
}
public class Name
{
String name;
public void getName(String n)
{
name = n;
}
public String toString()
{
return name;
}
}
public class Date
{
public String date;
public String date1;
public void getDate(int d, int m, int y)
{
date1 = (m + "/" + d + "/" + y);
}
public String toString()
{
return date1;
}
}
import java.util.Scanner;
public class Employee
{
private int number;
private Name name1 = new Name();
private Address address1 = new Address();
private Date hireDate = new Date();
String number1;
public void getDate1(int d, int m, int y)
{
hireDate.getDate(d, m, y);
}
public void getID(int x)
{
number = x;
}
public void setName( String n)
{
name1.getName(n);
}
public void getAddress(String a)
{
address1.address = a;
}
String z;
public String toString()
{
number1 = String.valueOf(number);
String name2 = String.valueOf(name1);
String address2 = String.valueOf(address1);
String hireDate2 = String.valueOf(hireDate);
z = number1 + " " + name2 + " " + address2 + " " + hireDate2;
return z;
}
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.println("Please enter amount of Employees: ");
int input1 = input.nextInt();
input.nextLine();
for (int i = 0; i < input1; i++)
{
Employee [] employees = new Employee[4];
System.out.println("Please enter the employee ID: ");
int employeeID = input.nextInt();
input.nextLine();
employees[0] = new Employee();
employees[0].getID(employeeID);
System.out.println("Please enter the employees Name: ");
String name2 = input.nextLine();
employees[1] = new Employee();
employees[1].setName(name2);
System.out.println("Please enter the employee's address: ");
String address2 = input.nextLine();
employees[2] = new Employee();
employees[2].getAddress(address2);
System.out.println("please enter hire date, day (1-31),");
System.out.print("month (1-12), year (1901 - 2019) in order on seperate");
System.out.print(" lines: ");
int input2 = input.nextInt();
int input3 = input.nextInt();
int input4 = input.nextInt();
employees[3] = new Employee();
employees[3].getDate1(input2, input3, input4);
for (int p = 0; p < employees.length; p++)
{
System.out.println(employees[p]);
}
}
}
}
I have create classes which were needed. You can change them but you are creating employee object every time. I have corrected the code debug it and you will know what was wrong.
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;
class Name {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
class Address {
private String address;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
public class Employee {
private int number;
private Name name1 = new Name();
private Address address1 = new Address();
private Date hireDate = new Date();
String number1;
public void getDate1(int d, int m, int y) {
Calendar calendar = Calendar.getInstance();
calendar.set(y, m, d);
hireDate = calendar.getTime();
}
public void getID(int x) {
number = x;
}
public void setName(String n) {
name1.setName(n);
}
public void getAddress(String a) {
address1.setAddress(a);
}
String z;
public String toString() {
number1 = String.valueOf(number);
String name2 = name1.getName();
String address2 = address1.getAddress();
String hireDate2 = String.valueOf(hireDate);
z = number1 + " " + name2 + " " + address2 + " " + hireDate2;
return z;
}
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter amount of Employees: ");
int input1 = input.nextInt();
input.nextLine();
Employee[] employees = new Employee[input1];
for (int i = 0; i < input1; i++) {
System.out.println("Please enter the employee ID: ");
int employeeID = input.nextInt();
input.nextLine();
employees[i] = new Employee();
employees[i].getID(employeeID);
System.out.println("Please enter the employees Name: ");
String name2 = input.nextLine();
employees[i].setName(name2);
System.out.println("Please enter the employee's address: ");
String address2 = input.nextLine();
employees[i].getAddress(address2);
System.out.println("please enter hire date, day (1-31),");
System.out.print("month (1-12), year (1901 - 2019) in order on seperate");
System.out.print(" lines: ");
int input2 = input.nextInt();
int input3 = input.nextInt();
int input4 = input.nextInt();
employees[i].getDate1(input2, input3, input4);
System.out.println(employees[i]);
}
}
}
So i have 3 classes, and one that runs all the code. A student class, a Graduate student class and an undergraduate class, and a class called lab 4 that runs the code. The code asks for how many grad students and how many undergrad students there are, then asks the user to input all the information for that number of each. After all the info is inputed, the under grad or grad student objects are added to an array list of students. after all the students are added, then prints all the information. However when i input all the information, the array does not print, the program terminates. How do i get the array to print out?
Code:
Lab 4: creates the student objects, array list, adds them to the array, and the prints all information for objects added to the array list
import java.util.ArrayList;
import java.util.Scanner;
public class Lab04 {
public static void main(String[] args) {
ArrayList <Student> studentList = new ArrayList <Student>();
Scanner s = new Scanner(System.in);
System.out.println("How many Graduate Students do you want to store?");
int numOfStudents = s.nextInt();
s.nextLine();
for (int i = 0; i < numOfStudents; i++) {
System.out.println("What is the student's name?");
String name = s.nextLine();
System.out.println("What is the student's GPA?");
double GPA = s.nextDouble();
s.nextLine();
System.out.println("What is the student's ID?");
String ID = s.nextLine();
System.out.println("What is the student's High School?");
String highSchool = s.nextLine();
System.out.println("What is the student's graduate major?");
String gradMajor = s.nextLine();
System.out.println("What is the student's undergraduate major?");
String underMajor = s.nextLine();
System.out.println("What is the student's undergradute school? ");
String underSchool = s.nextLine();
GraduateStudent gradStu = new GraduateStudent(name, GPA, ID, highSchool, gradMajor, underMajor,
underSchool);
studentList.add(gradStu);
}
System.out.println("How many UnderGraduate students are there?");
int numOfUnder = s.nextInt();
s.nextLine();
for (int j = 0; j < numOfUnder; j++) {
System.out.println("What is the student's name?");
String name = s.nextLine();
System.out.println("What is the student's GPA?");
double GPA = s.nextDouble();
s.nextLine();
System.out.println("What is the student's ID?");
String ID = s.nextLine();
System.out.println("What is the student's High School?");
String highSchool = s.nextLine();
System.out.println("What is the student's major?");
String major = s.nextLine();
System.out.println("What the student's minor?");
String minor = s.nextLine();
UnderGraduate UnderGrad = new UnderGraduate(name, GPA, ID, highSchool, major, minor);
studentList.add(UnderGrad);
}
for (int j = 0; j < studentList.size(); j++) {
(studentList.get(j)).getStudentInformation();
}
}
}
Student Class:
public class Student {
private String name;
private double gpa;
private String id;
private String highSchool;
//private String major;
//private String minor;
public Student() {
name = "";
gpa = 0.0;
id = "";
highSchool = "";
//major = "";
//minor = "";
}
public Student(String name, double gpa, String id, String highSchool){
this.name = name;
this.gpa = gpa;
this.id = id;
this.highSchool = highSchool;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getGpa() {
return gpa;
}
public void setGpa(double gpa) {
this.gpa = gpa;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getHighSchool() {
return highSchool;
}
public void setHighSchool(String highSchool) {
this.highSchool = highSchool;
}
public String getStudentInformation() {
String result = "Name: " + name + " GPA: " + gpa + " ID: " + id
+ " High School: " + highSchool;
return result;
}
}
graduate Class:
public class GraduateStudent extends Student {
private String gradMajor;
private String underMajor;
private String underSchool;
public GraduateStudent(String name, double gpa, String id, String highSchool,
String gradMajor, String underMajor, String underSchool) {
super(name, gpa, id, highSchool);
this.gradMajor = gradMajor;
this.underMajor = underMajor;
this.underSchool = underSchool;
}
public String getGradMajor() {
return gradMajor;
}
public void setGradMajor(String gradMajor) {
this.gradMajor = gradMajor;
}
public String getUnderMajor() {
return underMajor;
}
public void setUnderMajor(String underMajor) {
this.underMajor = underMajor;
}
public String getUnderSchool() {
return underSchool;
}
public void setUnderSchool(String underSchool) {
this.underSchool = underSchool;
}
#Override
public String getStudentInformation() {
String result = super.getStudentInformation()+
"Graduate Major: " + gradMajor + "Undergraduate Major: " + underMajor +
"Undergraduate School: " + underSchool;
return result;
}
}
Because you're not printing anything. Change
for (int j = 0; j < studentList.size(); j++) {
(studentList.get(j)).getStudentInformation();
}
to
for (int j = 0; j < studentList.size(); j++) {
System.out.println((studentList.get(j)).getStudentInformation());
}
When you ask getStudentInformation, it returns a String, what you want to do now is to System.out.println(...) this String object
I have created a simple program which outputs student details. Ideally I would like to give the user an option to add both courses. Will this require a lot of messing about changing code? If not can someone help?
class Student
{
public static void main(String[]args)//The main method; starting point of the program.
{
Scanner input = new Scanner(System.in);
String surName, foreName, courseName;
int age,telephone;
System.out.println("\t\t\t***********************************************");
System.out.println("\t\t\tWelcome to the Mobile College's Student Records");
System.out.println("\t\t\t***********************************************");
System.out.println("\nHow many students would you like to add?");
int noStudents = input.nextInt();
Stu [] TheStu = new Stu [noStudents];
for (int x = 0; x < noStudents; x++)
{
System.out.println("Please enter Surname: ");
surName = input.next();
System.out.println("Please enter Forename: ");
foreName = input.next();
System.out.println("Please enter Age: ");
age = input.nextInt();
System.out.println("Please enter Telephone No. ");
telephone = input.nextInt();
System.out.println("Which course do you want to add the student to? .......Literacy or Numeracy ");
courseName = input.next();
TheStu [x] = new Stu (surName, foreName, age, telephone, courseName);
}
for (int y = 0; y < noStudents; y++)
{
System.out.println("\t\t\t***********************************************");
System.out.println ("\t\t\tName: " + TheStu[y].getfName() + " " + TheStu[y].getsName());
System.out.println ("\t\t\tAge: " + TheStu[y].getstuAge());
System.out.println ("\t\t\tTelephone No. 0" + TheStu[y].getphone());
System.out.println ("\t\t\tEnrolled on the " + TheStu[y].getcourseType() + " Course.");
System.out.println("\t\t\t***********************************************");
}
}// end of class
}
class Stu
{
private String sName;
private String fName;
private int stuAge;
private int phone;
private String courseType;
Stu (String s, String f, int a, int p, String c)
{
sName = s;
fName = f;
stuAge = a;
phone = p;
courseType = c;
}
String getsName()
{
return sName;
}
String getfName()
{
return fName;
}
int getstuAge()
{
return stuAge;
}
int getphone()
{
return phone;
}
String getcourseType()
{
return courseType;
}
}
If you want something pretty basic, you could change your courses into a String array so you could store both courses. Also when asking the user to input a course name, you could have an ALL option, so you automatically register the student for all courses. See below for a slightly modified version of your code :
import java.util.Scanner;
class Student
{
public static void main(String[] args)//The main method; starting point of the program.
{
Scanner input = new Scanner(System.in);
String surName, foreName, courseName;
String[] courses = new String[]{};
int age,telephone;
System.out.println("\t\t\t***********************************************");
System.out.println("\t\t\tWelcome to the Mobile College's Student Records");
System.out.println("\t\t\t***********************************************");
System.out.println("\nHow many students would you like to add?");
int noStudents = input.nextInt();
Stu [] TheStu = new Stu [noStudents];
for (int x = 0; x < noStudents; x++)
{
System.out.println("Please enter Surname: ");
surName = input.next();
System.out.println("Please enter Forename: ");
foreName = input.next();
System.out.println("Please enter Age: ");
age = input.nextInt();
System.out.println("Please enter Telephone No. ");
telephone = input.nextInt();
System.out.println("Which courses do you want to add the student to? .......Literacy or Numeracy or both ");
courseName = input.nextLine();
// change to either upper case or lower case for easy treatment
courseName = courseName.toUpperCase();
// Also verify that the user entered a valid course name
if(courseName.equals("LITERACY")){
courses = new String[]{"LITERACY"};
} else if(courseName.equals("NUMERACY")){
courses = new String[]{"NUMERACY"};
} else if(courseName.equals("BOTH")){
courses = new String[]{"LITERACY", "NUMERACY"};
} else{
System.out.println("Error : You entered an invalid option.... \n This student won't be registered for any courses");
}
TheStu [x] = new Stu (surName, foreName, age, telephone, courses);
}
for (int y = 0; y < noStudents; y++)
{
System.out.println("\t\t\t***********************************************");
System.out.println ("\t\t\tName: " + TheStu[y].getfName() + " " + TheStu[y].getsName());
System.out.println ("\t\t\tAge: " + TheStu[y].getstuAge());
System.out.println ("\t\t\tTelephone No. 0" + TheStu[y].getphone());
System.out.println ("\t\t\tEnrolled in the following courses : ");
courses = TheStu[y].getcourseTypes();
for(int i = 0; i < courses.length; i++){
System.out.println(courses[i]);
}
if(courses.length < 1){
System.out.println("No Courses");
}
System.out.println("\t\t\t***********************************************");
}
}// end of class
}
class Stu
{
private String sName;
private String fName;
private int stuAge;
private int phone;
private String[] courseTypes;
Stu (String s, String f, int a, int p, String[] c)
{
sName = s;
fName = f;
stuAge = a;
phone = p;
courseTypes = c;
}
String getsName()
{
return sName;
}
String getfName()
{
return fName;
}
int getstuAge()
{
return stuAge;
}
int getphone()
{
return phone;
}
String[] getcourseTypes()
{
return courseTypes;
}
}
I tried as much as possible not to make any serious changes to your code as i assume you're a beginner, but there are a lot of changes you could make to improve your code. Happy Coding :)
When you ask for the course name, keep asking until they have entered in a sentinal value. Inside Stu keep an List<String> courseTypes. Store the entered courses in courseTypes. Also, you may want to add a set value to some of the fields in Stu. What if their phone number changes?
I created a super class called Employee, with a subclass called ProductionWorker and a driver called ProductionWorkerDriver. The program takes my entered info and returns the String values from the Employee class, but not the double and int values from the ProductionWorker class. The program I'm using said I had to initialize the values of those as 0, and I'm thinking that's why they show up as zero when compiled. However, the program won't compile without that, so I'm not sure what to do.
public class Employee {
private String name;
private String employeeNumber;
private String hireDate;
public Employee(String n, String num, String date) {
name = n;
employeeNumber = num;
hireDate = date;
}
public Employee() {
name = "";
employeeNumber = "";
hireDate = "";
}
public void setName(String n) {
name = n;
}
public void setEmployeeNumber(String e) {
employeeNumber = e;
}
public void setHireDate(String h) {
hireDate = h;
}
public String getName() {
return name;
}
public String getEmployeeNumber() {
return employeeNumber;
}
public String getHireDate() {
return hireDate;
}
public String toString() {
String str = "Employee Name: " + name
+ "\nEmployee #: " + employeeNumber
+ "\nHire Date: " + hireDate;
return str;
}
} //end of Employee class
//beginning of ProductionWorker class
import java.text.DecimalFormat;
public class ProductionWorker extends Employee {
private int shift;
private double payRate;
public int DAY_SHIFT = 1;
public int NIGHT_SHIFT = 2;
public ProductionWorker(String n, String num, String date, int sh, double rate) {
super(n, num, date);
shift = sh;
payRate = rate;
}
public ProductionWorker() {
}
public void setShift(int s) {
shift = s;
}
public void setPayRate(double p) {
payRate = p;
}
public int getShift() {
return shift;
}
public double getPayRate() {
return payRate;
}
public String toString() {
DecimalFormat dollar = new DecimalFormat("#,##0.00");
String str = super.toString() + "\nShift: " + shift
+ "\nPay Rate: $" + dollar.format(payRate);
return str;
}
}//end of ProductionWorker class
//beginning of ProductionWorkerDriver
import java.util.Scanner;
public class ProductionWorkerDriver {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String name = null;
String employeeNumber = null;
String hireDate = null;
int shift = 0;
double payRate = 0;
int DAY_SHIFT = 1;
int NIGHT_SHIFT = 2;
Employee info = new Employee(name, employeeNumber, hireDate);
System.out.println("Employee Name:");
name = keyboard.nextLine();
System.out.println("Employee #:");
employeeNumber = keyboard.nextLine();
System.out.println("Hire Date:");
hireDate = keyboard.nextLine();
ProductionWorker info2 = new ProductionWorker(name, employeeNumber, hireDate, shift, payRate);
System.out.println("Shift 1 or 2:");
shift = keyboard.nextInt();
System.out.println("Pay Rate:");
payRate = keyboard.nextDouble();
System.out.println(info2.toString());
}
}//end of ProductionWorkerDriver
You're not doing anything with the data you've entered:
System.out.println("Shift 1 or 2:");
shift = keyboard.nextInt();
System.out.println("Pay Rate:");
payRate = keyboard.nextDouble();
... the shift and payRate variables aren't used again. Changing the values of these local variables doesn't change the values in the instance that you created earlier using the same variables.
You should either be calling:
info2.setShift(shift);
info2.setPayRate(payRate);
... or better, wait until after you've asked those questions before you construct the instance. You're also not using your info variable at all. Your entire main method can be improved to:
Scanner keyboard = new Scanner(System.in);
System.out.println("Employee Name:");
String name = keyboard.nextLine();
System.out.println("Employee #:");
String employeeNumber = keyboard.nextLine();
System.out.println("Hire Date:");
String hireDate = keyboard.nextLine();
System.out.println("Shift 1 or 2:");
int shift = keyboard.nextInt();
System.out.println("Pay Rate:");
double payRate = keyboard.nextDouble();
ProductionWorker worker =
new ProductionWorker(name, employeeNumber, hireDate, shift, payRate);
System.out.println(worker);
Notice how in each case we don't declare a variable until we need it.
Note that the fact that your employee number and your hire date are both String values is a bit of a worry, and it's a bad idea to use double for currency values - get into the habit of using BigDecimal, or use an integer to represent a number of cents/pennies/whatever.
This:
System.out.println("Shift 1 or 2:");
shift = keyboard.nextInt();
System.out.println("Pay Rate:");
payRate = keyboard.nextDouble();
Will update the shift and payRate of your main method:
public static void main(String[] args)
{
//...
int shift = 0;
double payRate = 0;
Because you're outputting the values from the ProductionWorker, and those values are never updated, it will always output 0. Simply because you initialize ProductionWorker with those variables does not mean that the reference shift in the main method will point to the same place in memory as the reference shift inside ProductionWorker.
Each time I run this code it gets to where it asks for student id and it prints out the student id part and the homework part. Why? I am trying to do get a string for name, id, homework, lab, exam, discussion, and project then in another class I am splitting the homework, lab, and exam strings into arrays then parsing those arrays into doubles. After I parse them I total them in another method and add the totals with project and discussion to get a total score.
import java.util.Scanner;
import java.io.*;
public class GradeApplication_Kurth {
public static void main(String[] args) throws IOException
{
Student_Kurth one;
int choice;
boolean test = true;
do
{
Scanner keyboard = new Scanner(System.in);
PrintWriter outputFile = new PrintWriter("gradeReport.txt");
System.out.println("Please select an option: \n1. Single Student Grading \n2. Class Grades \n3. Exit");
choice = keyboard.nextInt();
switch (choice)
{
case 1 :
System.out.println("Please enter your Student name: ");
String name = keyboard.next();
System.out.println("Please enter you Student ID: ");
String id = keyboard.nextLine();
System.out.println("Please enter the 10 homework grades seperated by a space: ");
String homework = keyboard.next();
System.out.println("Please enter the 6 lab grades seperated by a space: ");
String lab = keyboard.nextLine();
System.out.println("Please enter the 3 exam grades seperated by a space: ");
String exam = keyboard.nextLine();
System.out.println("Please enter the discussion grade: ");
double discussion = keyboard.nextDouble();
System.out.println("Please enter the project grade: ");
double project = keyboard.nextDouble();
one = new Student_Kurth(name, id, homework, lab, exam, discussion, project);
outputFile.println(one.toFile());
System.out.println(one);
break;
case 2 :
File myFile = new File("gradeReport.txt");
Scanner inputFile = new Scanner(myFile);
while(inputFile.hasNext())
{
String str = inputFile.nextLine();
System.out.println("\n" + str);
}
break;
case 3 :
test = false;
keyboard.close();
outputFile.close();
System.exit(0);
}
} while (test = true);
}
}
second class
public class Student_Kurth
{
public String homework;
public String name;
public String id;
public String lab;
public String exam;
public double project;
public double discussion;
public double[] hw = new double[10];
public double[] lb = new double[6];
public double[] ex = new double[3];
public final double MAX = 680;
public double percentage;
public String letterGrade;
public Student_Kurth()
{
homework = null;
name = null;
id = null;
lab = null;
exam = null;
project = 0;
discussion = 0;
}
public Student_Kurth(String homework, String name, String id, String lab, String exam, double project, double discussion)
{
this.homework = homework;
this.name = name;
this.id = id;
this.lab = lab;
this.exam = exam;
this.project = project;
this.discussion = discussion;
}
public void Homework(String homework)
{
String delims = " ";
String[] tokens = this.homework.split(delims);
int tokenCount = tokens.length;
for(int i = 0; i < tokenCount; i++)
{
hw[i] = Double.parseDouble(tokens[i]);
}
}
public void Lab(String lab)
{
String delims = " ";
String[] tokens = this.lab.split(delims);
int tokenCount = tokens.length;
for(int i = 0; i < tokenCount; i++)
{
lb[i] = Double.parseDouble(tokens[i]);
}
}
public void Exam(String exam)
{
String delims = " ";
String[] tokens = this.exam.split(delims);
int tokenCount = tokens.length;
for(int i = 0; i < tokenCount; i++)
{
ex[i] = Double.parseDouble(tokens[i]);
}
}
public double getHomeworkTotal(double[] hw)
{
double hwTotal = 0;
for(int i = 0; i < hw.length; i++)
{
hwTotal += hw[i];
}
return hwTotal;
}
public double getLabTotal(double[] lb)
{
double lbTotal = 0;
for(int i = 0; i < lb.length; i++)
{
lbTotal += lb[i];
}
return lbTotal;
}
public double getExamTotal(double[] ex)
{
double exTotal = 0;
for(int i = 0; i < ex.length; i++)
{
exTotal += ex[i];
}
return exTotal;
}
public double getTotalScores(double getExamTotal, double getLabTotal, double getHomeworkTotal)
{
return getExamTotal + getLabTotal + getHomeworkTotal + this.project + this.discussion;
}
public double getPercentage(double getTotalScores)
{
return 100 * getTotalScores / MAX;
}
public String getLetterGrade(double getPercentage)
{
if(getPercentage > 60)
{
if(getPercentage > 70)
{
if(getPercentage > 80)
{
if(getPercentage > 90)
{
return "A";
}
else
{
return "B";
}
}
else
{
return "C";
}
}
else
{
return "D";
}
}
else
{
return "F";
}
}
public void getLetter(String getLetterGrade)
{
letterGrade = getLetterGrade;
}
public void getPercent(double getPercentage)
{
percentage = getPercentage;
}
public String toFile()
{
String str;
str = " " + name + " - " + id + " - " + percentage + " - " + letterGrade;
return str;
}
public String toString()
{
String str;
str = "Student name: " + name + "\nStudent ID: " + id + "\nTotal Score: " + getTotalScores(getExamTotal(ex), getLabTotal(lb), getHomeworkTotal(hw)) +
"\nMax Scores: " + MAX + "Percentage: " + percentage + "Grade: " + letterGrade;
return str;
}
}
At the end of the switch, you have
while ( test = true)
You probably want to change that to
while ( test == true)
Also, take these lines out of the loop:
Scanner keyboard = new Scanner(System.in);
PrintWriter outputFile = new PrintWriter("gradeReport.txt");
In addition to Ermir's answer, this line won't capture all the grades:
System.out.println("Please enter the 10 homework grades seperated by a space: ");
String homework = keyboard.next();
Keyboard.next only reads until the next delimiter token, so if you want to capture 10 grades separated by spaces you need capture the whole line, like:
System.out.println("Please enter the 10 homework grades separated by a space: ");
String homework = keyboard.nextLine();