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?
Related
Can someone tell me why my baggage won't print?
For passenger name I enter, say, John.
For country code I enter: BI
For flight number I enter: 095
For number of baggage I can enter any amount.
Let's say I enter: John, BI, 095, 3.
This is what I get: [John with baggage(s) [, , ]] when I should be getting
[John with baggage(s) [BI0950, BI0951, BI0952]]
Sorry if the code is quite messy.
It's amended. Thanks guys.
import java.util.*;
public class baggageSys{
public static String getUser_command(){
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter command B-baggage, n-next, q-quit");
String s = keyboard.nextLine();
return s;
}
public static String getUser_flight(){
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the flight number");
String s = keyboard.nextLine();
return s;
}
public static String getPassenger(){
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter passenger name");
String s = keyboard.nextLine();
return s;
}
public static String getUser_country(){
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the country code");
String s = keyboard.nextLine();
return s;
}
public static int getUser_number(){
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter number of baggage");
int s = keyboard.nextInt();
return s;
}
public static String next(ListIterator<Passenger> passenger){
String k = "";
passenger.next();
return k;
}
public static String makeBaggage(String country, String flight, int num){
return country + flight + num;
}
public static void main(String args[]) {
LinkedList<Passenger> passenger = new LinkedList<Passenger>();
ListIterator<Passenger> iterator = passenger.listIterator();
LinkedList<String> baggage = new LinkedList<String>();
String command = "";
while (!command.equals("q")){
command = getUser_command();
if(command.equals("B") || command.equals("b")){
String p = "";
p = getPassenger();
passenger.add(new Passenger(p));
// command = getUser_command();
String country = "";
country = getUser_country();
String flight = "";
flight = getUser_flight();
int amount = 0;
amount = getUser_number();
String[] bg = new String[amount];
for(int i = 0; i < amount; i++){
bg[i] = makeBaggage(country, flight, i);
baggage.add(bg[i]);
System.out.println(bg[i]);
passenger.getLast().setBaggages(baggage);
}
System.out.println(passenger);
} else if(command.equals("n")){
next(iterator);
}
else
System.out.println("Enter 'q' to end the program");
}
}
public static class Passenger {
String passengers;
List<String> baggage;
public Passenger(String passengers) {
this.passengers = passengers;
baggage = Collections.emptyList();
}
public void setBaggages(List<String> baggage) {
this.baggage = baggage;
}
#Override
public String toString() {
return passengers + " with baggage(s) " + baggage;
}
}
}
You're not returning anything in your makeBaggage method, as you can see after the loop it returns the x variable which is not either set inside the loop, in this case your loop is useless.
public static String makeBaggage(String country, String flight, int num){
String x = "";
for(int i = 0; i < num; i++){
String[] bgs = new String[num];
bgs[i] = country + flight + i;
// System.out.println(bgs[i]);
}
return x;
}
I think this is the one you're looking for:
public static String makeBaggage(String country, String flight, int num){
return country + flight + num;
}
For this specific line in your code:
for(int i = 0; i < amount; i++){
String[] bg = new String[amount];
bg[i] = makeBaggage(country, flight, amount);
baggage.add(bg[i]);
System.out.println(bg[i]);
...
Move the String[] bg = new String[amount]; declaration outside of the for loop and instead of supplying the amount in the makeBaggage method, use the loop counter instead as follows: bg[i] = makeBaggage(country, flight, i);
String[] bg = new String[amount];
for(int i = 0; i < amount; i++){
bg[i] = makeBaggage(country, flight, i);
baggage.add(bg[i]);
System.out.println(bg[i])
..
I think that should do it. Also, your code could be greatly improved, and that would be your tasks.
I have created 2 java files: XCompanyShortlist.java and StudentDemo.java. The XCompanyShortlist.java contains the main method and all the user input like Student Registration No., Name, Semester, GPA, CGPA, Branch Name, Placement status and Internship status.
The StudentDemo.java has a superclass StudentDemo which initializes Reg. No., Name, Semester, GPA, CGPA using parameterized constructor and it also contains a method display() which displays all there informations.
A class BranchStudent extends StudentDemo class and contains an extra String named BranchName. This class also contains a display() method which calls the display() method in the superclass and also prints the BranchName. Another class StudentPlacement contains variables for InternshipStatus, PlacementStatus, and an array of preferred company list.
Here is the StudentDemo.java file code:
class StudentDemo {
long RegNo;
String fname;
short sem;
float gpa;
float cgpa;
StudentDemo() {
RegNo = 0;
fname = "";
sem = 0;
gpa = (float) 0.0;
cgpa = (float)0.0;
}
StudentDemo(long RegNo, String fname, short sem, float gpa, float cgpa) {
this.RegNo = RegNo;
this.fname = fname;
this.sem = sem;
this.gpa = gpa;
this.cgpa = cgpa;
}
StudentDemo(StudentDemo obj) {
RegNo = obj.RegNo;
fname = obj.fname;
sem = obj.sem;
gpa = obj.gpa;
cgpa = obj.cgpa;
}
void display() {
System.out.println("------------------------------------------");
System.out.println("Registration No. :"+RegNo);
System.out.println("Full Name: "+fname);
System.out.println("Semester: "+sem);
System.out.println("GPA: "+gpa);
System.out.println("CGPA: "+cgpa);
System.out.println("------------------------------------------");
}
}
class BranchStudent extends StudentDemo {
public String BranchName;
BranchStudent(long RegNo,String fname,short sem,float gpa,float cgpa,String BranchName) {
super(RegNo,fname,sem,gpa,cgpa);
this.BranchName = BranchName;
}
BranchStudent() {
super();
BranchName = "CSE";
}
BranchStudent(BranchStudent obj) {
super(obj);
BranchName = obj.BranchName;
}
void display() {
super.display();
System.out.println("Student Branch: "+BranchName);
}
}
class StudentPlacement extends BranchStudent {
String compList[];
int StatusPlacement, StatusIntern;
StudentPlacement() {
super();
StatusPlacement = 0;
StatusIntern = 0;
compList = new String[3];
}
StudentPlacement(StudentPlacement obj) {
super(obj);
StatusPlacement = obj.StatusPlacement;
StatusIntern = obj.StatusIntern;
compList = obj.compList;
}
StudentPlacement(long RegNo, String fname, short sem, float gpa, float cgpa, String BranchName,String compList[], int StatusPlacement,int StatusIntern) {
super(RegNo, fname, sem, gpa, cgpa, BranchName);
this.compList = compList;
this.StatusPlacement = StatusPlacement;
this.StatusIntern = StatusIntern;
}
}
Here is the XCompanyShortlist.java file code:
import java.util.Scanner;
public class XCompanyShortlist {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please Enter The Number Of Students: ");
int n = sc.nextInt();
StudentPlacement obj[] = new StudentPlacement[n];
for(int i = 0; i < n; i++) {
obj[i] = new StudentPlacement();
}
System.out.println("Please Enter The Student Details: ");
for(int i = 0; i < n; i++) {
System.out.print("Please Enter The Reg. No. :");
long RegNo = sc.nextLong();
sc.nextLine();
System.out.print("Please Enter The Full Name: ");
String fname = sc.nextLine();
System.out.print("Please Enter The Semester: ");
short sem = sc.nextShort();
System.out.print("Please Enter The GPA: ");
float gpa = sc.nextFloat();
System.out.print("Please Enter The CGPA: ");
float cgpa = sc.nextFloat();
System.out.print("Please Enter Branch Name:");
String branchName = sc.nextLine();
sc.nextLine();
System.out.println("Please Enter 3 Preferred Choice: ");
String compList[] = new String[3];
for(int x = 0; x < 3; x++) {
compList[x] = sc.nextLine();
}
System.out.print("Please Enter The Status Of Placement(0/1): ");
int statusPlacement = sc.nextInt();
System.out.print("Please Enter Status Of Internship(0/1): ");
int statusIntern = sc.nextInt();
obj[i] = new StudentPlacement(RegNo,fname,sem,gpa,cgpa,branchName,compList,statusPlacement,statusIntern);
System.out.println();
}
for(int i = 0; i < n; i++) {
obj[i].display();
}
sc.close();
}
}
The problem I am facing is that all the student details from the StudentDemo superclass is being dislayed but the subclass BranchStudent is not printing the BranchName. I am unable to find the problem in my code.
OUTPUT:
Please Enter The Number Of Students:
1
Please Enter The Student Details:
Please Enter The Reg. No. :159101046
Please Enter The Full Name: Bitan Basak
Please Enter The Semester: 3
Please Enter The GPA: 8.86
Please Enter The CGPA: 8.64
Please Enter Branch Name:CSE
Please Enter 3 Preferred Choice:
HP
Dell
Microsoft
Please Enter The Status Of Placement(0/1): 0
Please Enter Status Of Internship(0/1): 0
------------------------------------------
Registration No. :159101046
Full Name: Bitan Basak
Semester: 3
GPA: 8.86
CGPA: 8.64
------------------------------------------
Student Branch:
This is the output given by my program. As you can see the Student Branch is not being printed. I am unable to understand why.
From what I can tell the issue has nothing to do with inheritance but rather that you are feeding an empty line to the constructor.
This means something is wrong with the usage of the Scanner.nextLine() method. If I change your code to this:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please Enter The Number Of Students: ");
int n = sc.nextInt();
StudentPlacement obj[] = new StudentPlacement[n];
for(int i = 0; i < n; i++) {
obj[i] = new StudentPlacement();
}
System.out.println("Please Enter The Student Details: ");
for(int i = 0; i < n; i++) {
System.out.print("Please Enter The Reg. No. :");
long RegNo = sc.nextLong();
sc.nextLine();
System.out.print("Please Enter The Full Name: ");
String fname = sc.nextLine();
System.out.print("Please Enter The Semester: ");
short sem = sc.nextShort();
System.out.print("Please Enter The GPA: ");
float gpa = sc.nextFloat();
System.out.print("Please Enter The CGPA: ");
float cgpa = sc.nextFloat();
sc.nextLine();
System.out.print("Please Enter Branch Name:");
String branchName = sc.nextLine();
System.out.println("Please Enter 3 Preferred Choice: ");
String compList[] = new String[3];
for(int x = 0; x < 3; x++) {
compList[x] = sc.nextLine();
}
System.out.print("Please Enter The Status Of Placement(0/1): ");
int statusPlacement = sc.nextInt();
System.out.print("Please Enter Status Of Internship(0/1): ");
int statusIntern = sc.nextInt();
obj[i] = new StudentPlacement(RegNo,fname,sem,gpa,cgpa,branchName,compList,statusPlacement,statusIntern);
System.out.println();
}
for(int i = 0; i < n; i++) {
obj[i].display();
}
sc.close();
}
I.e. move the sc.nextLine() before the Branch Name input the scanner picks up the correct value from the console.
Hope that helps.
Greetings
in void display() method you are calling super display() method so the super display() method is calling not that branch display method and add this.branchname
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
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.
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();