I am having trouble with my program. It doesn't display the DoB when you enter it or give the age. Also it doesn't give the Max heart rate or targeted heart rate. Anyone know what I did wrong?
Here is the coding:
import java.util.*;
public class HealthProfile {
String firstName;
String lastName;
char gender;
int BirthMonth;
int BirthDay;
int BirthYear;
int height;
int weight;
public HealthProfile(String fName, String lName, char Genderr, int birthMonth, int birthDay, int birthYear, int heightt, int weightt){
firstName = fName;
lastName = lName;
gender = Genderr;
BirthMonth = birthMonth;
BirthDay = birthDay;
BirthYear = birthYear;
height = heightt;
weight = weightt;
}
HealthProfile() {
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getLastName() {
return lastName;
}
public void setGender(char gender) {
this.gender = gender;
}
public char getGender() {
return gender;
}
public void setBirthMonth(int BirthMonth) {
this.BirthMonth = BirthMonth;
}
public int getBirthMonth() {
return BirthMonth;
}
public void setBirthDay(int BirthDay) {
this.BirthDay = BirthDay;
}
public int getBirthDay() {
return BirthDay;
}
public void setBirthYear(int BirthYear) {
this.BirthYear = BirthYear;
}
public int getBirthYear() {
return BirthYear;
}
public void setHeight(int height) {
this.height = height;
}
public double getHeight() {
return height;
}
public void setWeight(int weight) {
this.weight = weight;
}
public double getWeight() {
return weight;
}
public int Age(){
Calendar now = Calendar.getInstance();
int nowYear = now.get(Calendar.YEAR);
int nowMonth = now.get(Calendar.MONTH);
int nowDay = now.get(Calendar.DATE);
int day = now.get(Calendar.DATE);
int month = now.get(Calendar.MONTH);
int year = now.get(Calendar.YEAR);
if (nowMonth > BirthMonth);
int Age = (nowYear-BirthYear);
return Age;
}
public double getBMI(){
return (weight * 703)/(height * height);
}
public int getMaxHeartRate(){
return 220-Age();
}
public double getTargetHeartRate(){
return getMaxHeartRate() * 0.85 + getMaxHeartRate() * 0.5;
}
}
Here is the test part:
import java.util.Scanner;
public class HealthProfileTest {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String firstName;
String lastName;
String DoB;
String theMonth;
String theDay;
String theYear;
char gender;
int month = 0;
int day = 0;
int year = 0;
double height;
double weight;
HealthProfile personalInfo = new HealthProfile();
System.out.println("Enter your first name: ");
personalInfo.setFirstName(input.nextLine());
System.out.println("Enter your last name: ");
personalInfo.setLastName(input.nextLine());
System.out.println("Male or female: ");
personalInfo.setGender(input.nextLine().charAt(0));
System.out.println("Enter your date of birth in mm/dd/yyyy format: ");
DoB = input.nextLine();
personalInfo.setBirthMonth(month);
personalInfo.setBirthDay(day);
personalInfo.setBirthYear(year);
theMonth = DoB.substring(0,2);
theDay = DoB.substring(3,5);
theYear = DoB.substring(6,10);
month = Integer.parseInt(theMonth);
day = Integer.parseInt(theDay);
year = Integer.parseInt(theYear);
System.out.println("Enter your height in inches: ");
height = input.nextInt();
personalInfo.setHeight((int)height);
System.out.println("Enter your weight in pounds: ");
weight = input.nextInt();
personalInfo.setWeight((int)weight);
System.out.println("Name: " + personalInfo.getFirstName() +" "+ personalInfo.getLastName());
System.out.println("Gender: " + personalInfo.getGender());
System.out.println("DoB: " + personalInfo.getBirthMonth() + "/" + personalInfo.getBirthDay() + "/" + personalInfo.getBirthYear());
System.out.println("Height: " + personalInfo.getHeight());
System.out.println("Weight: " + personalInfo.getWeight());
System.out.println("Age: " + personalInfo.Age());
System.out.println("BMI: " + personalInfo.getBMI());
System.out.printf("Max heart rate: ", personalInfo.getMaxHeartRate());
System.out.print(" ");
System.out.printf("Target heart rate: ", personalInfo.getTargetHeartRate());
System.out.println(" ");
System.out.println( "BMI VALUES" );
System.out.println("Underweight: Under 18.5");
System.out.println("Normal: 18.5-24.9 ");
System.out.println("Overweight: 25-29.9");
System.out.println("Obese: 30 or over");
}
}
Output (I am only showing the results that are not working):
DoB: 0/0/0
Age: 2013
Max heart rate:
Target heart rate:
For your DoB , you are setting you HealthProfile attrbibues values before actually calculating the day,month and year. Change this :
//month,day and year are not properly calcualted yet
personalInfo.setBirthMonth(month);
personalInfo.setBirthDay(day);
personalInfo.setBirthYear(year);
theMonth = DoB.substring(0,2);
theDay = DoB.substring(3,5);
theYear = DoB.substring(6,10);
month = Integer.parseInt(theMonth);
day = Integer.parseInt(theDay);
year = Integer.parseInt(theYear);
to
theMonth = DoB.substring(0,2);
theDay = DoB.substring(3,5);
theYear = DoB.substring(6,10);
month = Integer.parseInt(theMonth);
day = Integer.parseInt(theDay);
year = Integer.parseInt(theYear);
//month,day and year now have a proper value, so set it in your personalInfo
personalInfo.setBirthMonth(month);
personalInfo.setBirthDay(day);
personalInfo.setBirthYear(year);
You are not printing right:
System.out.printf("Max heart rate: ", personalInfo.getMaxHeartRate());
System.out.printf("Target heart rate: ", personalInfo.getTargetHeartRate());
should be:
System.out.printf("Max heart rate: %d", personalInfo.getMaxHeartRate());
System.out.printf("Max heart rate: %.1f", personalInfo.getTargetHaertRate());
Related
I can output the details from the student, but always when i do it displays
Exception in thread "main" java.lang.NullPointerException
at client.Client.main(Client.java:126)
and the program crashes.
The array is null , I don't why and I don't know how to fix that. Please help me to understand, the problem should be around here..
if (choice == 3) {
for (int a = 0; a < list.length; a++) { //To Display all current Student Information.
// list[i] = new student();
list[a].DisplayOutput();
}
Anyways here comes my code.
package client;
import java.util.Scanner;
public class Client {
//my infos
public static void AuthorInformation() {
System.out.print("__________________________________________\n"
+ "Student Name: xxxxxx xxxxxx\n"
+ "Student ID-Number: xxxxxx\n"
+ "Tutorial Timing: Wednesday 9:30 - 12:30 \n"
+ "Tutor Name: Mr xxxxxx\n\n"
+ "__________________________________________\n");
}
This is my client Class
public static void main(String[] args) {
AuthorInformation(); //calls the method for my information
student[] list = new student[20]; //my array
student student = new student();
int choice = 0; //variable for the choise of the menu
Scanner keyboard = new Scanner(System.in); //Scanner class
do { //MY menu in the do-while, so that it runs at least once while user enters 7(quit)
student.DisplayQuestions();
choice = keyboard.nextInt(); //takes the entered value from the user
if (choice == 1) {
System.out.println("Enter the Number of Students you want to store: ");//Enter amount of students to be stored
int studentNumber = keyboard.nextInt();
// student.addStudent();
for (int i = 0; i < studentNumber; i++) { //for loop is till the student number is achieved
list[i] = new student();
System.out.println("\nTitle of the student (eg, Mr, Miss, Ms, Mrs etc): ");
list[i].SetTitle(keyboard.next());
System.out.println("First name (given name)");
list[i].SetFirstName(keyboard.next());
System.out.println("A last name (family name/surname)");
list[i].SetFamilyName(keyboard.next());
System.out.println("Student number (ID):");
list[i].SetStudentID(keyboard.nextInt());
System.out.println("Enter the Day of birth(1-31): ");
list[i].SetDay(keyboard.nextInt());
System.out.println("Enter the Month of birth (1-12): ");
list[i].SetMonth(keyboard.nextInt());
System.out.println("Enter The Year of birth: ");
list[i].SetYear(keyboard.nextInt());
System.out.println("Students First Assignment Mark (0 - 100): ");
list[i].SetFirstMark(keyboard.nextInt());
System.out.println("Students Second Assignment Mark (0 - 100): ");
list[i].SetSecondMark(keyboard.nextInt());
System.out.println("Enter the mark of Student weekly practical work (0-10) ");
list[i].SetWeeklyMarks(keyboard.nextInt());
System.out.println("Please Enter the Marks for the final Exam(0 - 100): ");
list[i].SetFinalMark(keyboard.nextInt());
/* System.out.println("- - - - - - - - - - - - -");
System.out.println("Do you want to add another Student? (Yes/No)");
String a = keyboard.next();
if (a.equalsIgnoreCase("yes")) {
} else if (a.equalsIgnoreCase("no")) {
i = list.length + 1;
}*/
}
}
if (choice == 2) {
int x = 2;
double AverageNum = 0;
for (int p = 0; p < x; p++) { //This is to take the Average OverallMarks of all students
AverageNum += list[p].OverallMarking();
}
System.out.println("Total Average Of Overall Marks is :" + AverageNum / 2);
}
if (choice == 3) {
for (int a = 0; a < list.length; a++) { //To Display all current Student Information.
// list[i] = new student();
list[a].DisplayOutput();
}
}
if (choice == 4) { //To Display the distribution of grades awarded.
System.out.println("\nGrade Distribution: \n" + student.GetCounterHD() + " HDs\n" + student.GetCounterD() + " Ds\n" + student.GetCounterC() + " Cs\n" + student.GetCounterP() + " Ps\n" + student.GetCounterN() + " Ns\n");
}
if (choice == 5) {
System.out.println("Enter Student's ID Number to search for: "); // to take the id number from the user
int FindID = keyboard.nextInt();
boolean Found = false;
// to find with the student ID Number details of the student.
for (int i = 0; i < 10; i++) {
if (FindID == list[i].GetStudentID()) {
list[i].DisplayOutput();
Found = true;
break;
}
}
}
if (choice == 6) { //
System.out.println("Enter Student's Name to search for: ");
String SearchStudentName = keyboard.next(); //take the name of the student
boolean Found = false;
//To find the name of the student it loops till it has it or the limit of studentnumbers are achieved.
for (int i = 0; i < list.length; i++) {
if (SearchStudentName.equalsIgnoreCase(list[i].GetFirstName())) {
list[i].DisplayOutput();
Found = true;
break;
}
}
}
} while (choice != 7);
{ //while statement quit the program
System.out.println("\nYou Quit.");
}
}
}
And here is my student class
package client;
import java.util.Scanner;
public class student {
//The instance vriables for students (Title, first name, family name,
Student ID, date of birth in day month and year, first and second
assignment mark, mark of weekly practical work and final exam
private String Title;
private String FirstName;
private String FamilyName;
private long StudentID;
private int Day;
private int Month;
private int Year;
private float FirstMark;
private float SecondMark;
private float WeeklyMarks;
private float FinalMark;
//those private instance variables are for the calculation of (first and
second assignment mark, mark of weekly practical work and exam mark, final
mark and overall mark)
private float FirstMarkPercentage;
private float SecondMarkPercentage;
private float WeeklyMarksPercentage;
private float ExamPercentage;
private String FinalGrade;
private float OverallMarks = 0;
//those private instance variables are to count the the marks(
private int CounterN = 0;
private int CounterP = 0;
private int CounterC = 0;
private int CounterD = 0;
private int CounterHD = 0;
public student(String Title, String FirstName, String FamilyName, long StudentID, int Day, int Month, int Year, float FirstMark, float SecondMark, float WeeklyMarks, float FinalMark) {
this.Title = Title;
this.FirstName = FirstName;
this.FamilyName = FamilyName;
this.StudentID = StudentID;
this.Day = Day;
this.Month = Month;
this.Year = Year;
this.FirstMark = FirstMark;
this.SecondMark = SecondMark;
this.WeeklyMarks = WeeklyMarks;
this.FinalMark = FinalMark;
this.FinalGrade = FinalGrade;
}
//This Method is to display (Title, first name, family name, Student ID, date of birth in day month and year, first and second assignment mark, mark of weekly practical work and final exam)
public student() {
Title = "";
FirstName = "";
FamilyName = "";
StudentID = 0;
Day = 0;
Month = 0;
Year = 0;
FirstMark = 0;
SecondMark = 0;
WeeklyMarks = 0;
FinalMark = 0;
}
//The methods starting with Get...(), are to return the (Title, first name, family name, Student ID, date of birth in day month and year, first and second assignment mark, mark of weekly practical work and final exam and the marks N, P, C, D & HD)
public String GetTitle() {
return Title;
}
public String GetFirstName() {
return FirstName;
}
public String GetFamilyName() {
return FamilyName;
}
public long GetStudentID() {
return StudentID;
}
public int GetDay() {
return Day;
}
public int GetMonth() {
return Month;
}
public int GetYear() {
return Year;
}
public float GetFirstMark() {
return FirstMark;
}
public float GetSecondMark() {
return SecondMark;
}
public float GetWeeklyMarks() {
return WeeklyMarks;
}
public float GetFinalMark() {
return FinalMark;
}
public String GetFinalGrade() {
return FinalGrade;
}
public int GetCounterHD() {
return CounterHD;
}
public int GetCounterD() {
return CounterD;
}
public int GetCounterC() {
return CounterC;
}
public int GetCounterP() {
return CounterP;
}
public int GetCounterN() {
return CounterN;
}
public float GetOverallMarks() {
return OverallMarks;
}
//The methods starting with Set...(), are to set the (Title, first name, family name, Student ID, date of birth in day month and year, first and second assignment mark, mark of weekly practical work and final exam and the marks N, P, C, D & HD)
public void SetTitle(String Title) {
this.Title = Title;
}
public void SetFirstName(String FirstName) {
this.FirstName = FirstName;
}
public void SetFamilyName(String FamilyName) {
this.FamilyName = FamilyName;
}
public void SetStudentID(int StudentID) {
this.StudentID = StudentID;
}
public void SetDay(int Day) {
this.Day = Day;
}
public void SetMonth(int Month) {
this.Month = Month;
}
public void SetYear(int Year) {
this.Year = Year;
}
public void SetFirstMark(float FirstMark) {
this.FirstMark = FirstMark;
}
public void SetSecondMark(float SecondMark) {
this.SecondMark = SecondMark;
}
public void SetWeeklyMarks(float WeeklyMarks) {
this.WeeklyMarks = WeeklyMarks;
}
public void SetFinalMark(float FinalMark) {
this.FinalMark = FinalMark;
}
public void SetFinalGrade(String FinalGrade) {
this.FinalGrade = FinalGrade;
}
public void SetOverallMarks(float OverallMarks) {
this.OverallMarks = OverallMarks;
}
public boolean equals(student OtherStudent) {
return (this.FirstName.equalsIgnoreCase(OtherStudent.FirstName)) && (this.FamilyName.equalsIgnoreCase(OtherStudent.FamilyName));
}
//this method is for the calculation of (first and second assignment mark, mark of weekly practical work and exam mark, final mark and overall mark)
public float OverallMarking() {
FirstMarkPercentage = ((FirstMark / 100) * 20);
SecondMarkPercentage = ((SecondMark / 100) * 20);
WeeklyMarksPercentage = ((WeeklyMarks / 10) * 10);
ExamPercentage = ((FinalMark / 100) * 50);
OverallMarks = FirstMarkPercentage + SecondMarkPercentage + WeeklyMarksPercentage + ExamPercentage; //for the overall mark returns
return OverallMarks;
}
//this function arranges the grade calculations and returns the final grade
public String GradeCalculations() {
if (OverallMarks >= 80 && OverallMarks <= 100) { // if grade lies within this range print HD
FinalGrade = "HD";
CounterHD++;
} else if (OverallMarks >= 70 && OverallMarks < 80) { // if grade lies within this range print D
FinalGrade = "D";
CounterD++;
} else if (OverallMarks >= 60 && OverallMarks < 70) { // if grade lies within this range print C
FinalGrade = "C";
CounterC++;
} else if (OverallMarks >= 50 && OverallMarks < 60) { // if grade lies within this range print P
FinalGrade = "P";
CounterP++;
} else if (OverallMarks < 50 && OverallMarks >= 0) { // if grade lies within this range print N
FinalGrade = "N";
CounterN++;
}
return FinalGrade;
}
public void DisplayQuestions() {
System.out.println("\n Welcome to the Menu to perform one of the following operations (You must enter a number between 1-7):");
System.out.println("(1) To add the Student Information.");
System.out.println("(2) To Display the Output from the Average Overall Mark for students.");
System.out.println("(3) To Display all current Student Information.");
System.out.println("(4) To Display the distribution of grades awarded.");
System.out.println("(5) for entering a student ID Number To view all details of the student.");
System.out.println("(6) for entering a student name To view all details of the student.");
System.out.println("(7) Quit");
System.out.println("\n__________________________________________");
}
//This function displays the details of the student with before calculated marks.
public void DisplayOutput() {
System.out.println("\nName: " + GetTitle() + " " + GetFirstName() + " " + GetFamilyName());
System.out.println("Student ID: " + GetStudentID());
System.out.println("Date of Birth: " + GetDay() + "/" + GetMonth() + "/" + GetYear());
System.out.println("Assignment 1 Marks: " + GetFirstMark());
System.out.println("Assignment 2 Marks: " + GetSecondMark());
System.out.println("Weekly Practical Marks: " + GetWeeklyMarks());
System.out.println("Final Exam Marks: " + GetFinalMark());
System.out.println("Final Marks & Grade: " + OverallMarking() + "/" + GradeCalculations());
}
public void addStudent() {
/*Scanner keyboard = new Scanner(System.in);
for (int i = 0; i < list.length; i++) { //for loop is till the student number is achieved
list[i] = new student();
System.out.println("\nTitle of the student (eg, Mr, Miss, Ms, Mrs etc): ");
list[i].SetTitle(keyboard.next());
System.out.println("First name (given name)");
list[i].SetFirstName(keyboard.next());
System.out.println("A last name (family name/surname)");
list[i].SetFamilyName(keyboard.next());
System.out.println("Student number (ID):");
list[i].SetStudentID(keyboard.nextInt());
System.out.println("Enter the Day of birth(1-31): ");
list[i].SetDay(keyboard.nextInt());
System.out.println("Enter the Month of birth (1-12): ");
list[i].SetMonth(keyboard.nextInt());
System.out.println("Enter The Year of birth: ");
list[i].SetYear(keyboard.nextInt());
System.out.println("Students First Assignment Mark (0 - 100): ");
list[i].SetFirstMark(keyboard.nextInt());
System.out.println("Students Second Assignment Mark (0 - 100): ");
list[i].SetSecondMark(keyboard.nextInt());
System.out.println("Enter the mark of Student weekly practical work (0-10) ");
list[i].SetWeeklyMarks(keyboard.nextInt());
System.out.println("Please Enter the Marks for the final Exam(0 - 100): ");
list[i].SetFinalMark(keyboard.nextInt());
System.out.println("- - - - - - - - - - - - -");
System.out.println("Do you want to add another Student? (Yes/No)");
String a = keyboard.next();
if (a.equalsIgnoreCase("yes")) {
addStudent();
} else if (a.equalsIgnoreCase("no")) {
i=list.length+1;
}
}*/
}
}
The array isn't null.
The exception is thrown when you try to call a method on a null member of the array.
You iterate over the full array, but have not necessarily filled the entire array. Members that you have not assigned to reference an object are null.
for (int a = 0; a < list.length; a++) { //To Display all current Student Information.
// list[i] = new student();
list[a].DisplayOutput();
}
One fix would be to stop iterating after you've hit the first null.
for (int a = 0; a < list.length; a++) { //To Display all current Student Information.
// list[i] = new student();
student student = list[a];
if ( null == student ) {
break;
}
else {
list[a].DisplayOutput();
}
}
Another fix would be to remember in case 1 how many students were stored, and change the loop condition to reflect that.
for (int a = 0; a < cntStudents; a++) { //To Display all current Student Information.
By the way, in Java code it is almost universally accepted that:
Class names begin with an uppercase character.
Method names begin with a lowercase character.
QUESTION: I'm trying to find the win percentage (the formula for win percentage is wins/(wins + loses)). How do I take the values from wins and loses the user enters and add them to my Sysout function. Every time I run the program it displays:
East W L PCT
Braves 45 66 0.000000
Cubs 87 77 0.000000
So what I'm trying to do is get the actual values instead of it saying "0.0000000"
public class Team {
// Data fields...
private int wins;
private int loses;
private String teamName;
private String city;
private String division;
private double winPercentage;
// Getters and setters...
public int getWins() {
return wins;
}
public void setWins(int wins) {
this.wins = wins;
}
public int getLoses() {
return loses;
}
public void setLoses(int loses) {
this.loses = loses;
}
public String getTeamName() {
return teamName;
}
public void setTeamName(String teamName) {
this.teamName = teamName;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getDivision() {
return division;
}
public void setDivision(String division) {
this.division = division;
}
public double getWinPercentage() {
return wins/(wins + loses);
}
public void setWinPercentage(double winPercentage) {
this.winPercentage = winPercentage;
}
}
public class PlayoffSelectorClass extends Team{
public static void main(String[] args) {
List<Team> teams = new ArrayList<Team>();
for (int i = 0; i < 6; i++) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter team name: ");
String name = input.nextLine();
System.out.println("\nPlease enter the city " + name + " played in: ");
String city = input.nextLine();
System.out.println("\nPlease enter the division " + name + " play in: ");
String division = input.nextLine();
System.out.println("\nPlease enter the number of wins " + name + " has: ");
Integer wins = input.nextInt();
System.out.println("\nPlease enter the number of losses " + name + " has: ");
Integer loses = input.nextInt();
if (i < 5) {
System.out.println("\nEnter your next team...\n");
}
Team team = new Team();
team.setTeamName(name);
team.setCity(city);
team.setDivision(division);
team.setWins(wins);
team.setLoses(loses);
team.setWinPercentage(wins / (wins + loses));
teams.add(team);
}
System.out.println("East W L PCT\n");
for (Team team : teams) {
System.out.printf("%s\t%s\t%s\t%f\n",team.getTeamName() + " ", team.getWins() + " " , team.getLoses(), team.getWinPercentage());
}
}
}
The problem is here :
public double getWinPercentage() {
return wins/(wins + loses);
}
You are doing integer division, i.e only keep the int part of the result, and implicitly cast it to a double. So for example if:
wins = 10;
loses = 20;
then winPercentage == 10/30 == 0.33.. and you only keep the 0 and the cast it to double. Hence the 0.0000... etc What you can do instead is:
public double getWinPercentage() {
return wins/(double) (wins + loses);
}
I am working on my final and I got to the part I an mildly confused about.
I can't figure out if it's possible to call the Admin or Student inputs with it being outside of the if statement. I need to call the results in the 3rd and 4th option in the menu and I can't do it without it throwing errors.
public class MainEntry {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
int printMenu = 0;
while(printMenu != 5){
printMenu();
printMenu = console.nextInt();
if (printMenu == 1){
String firstName;
String lastName;
int year;
double[] grades;
double studentId;
String major;
int size;
System.out.println("How many students do you have? ");
size = console.nextInt();
Student newStudent = new Student();
int[] stud = new int[size];
for(int i = 0; i < stud.length; i++)
{
System.out.println("What is the students first name? ");
firstName = console.next();
newStudent.setFirstName(firstName);
System.out.println("What is the students last name? ");
lastName = console.next();
newStudent.setLastName(lastName);
System.out.println("What year are they in? ");
year = console.nextInt();
newStudent.setYear(year);
System.out.println("Enter in their grades: ");
grades = console.nextDouble();newStudent.setGrades(grades);
System.out.println("What is their Student ID number? ");
studentId = console.nextDouble();
newStudent.setStudentID(studentId);
System.out.println("What is the student's major? ");
major = console.next();
newStudent.setMajor(major);
}
}
else if (printMenu == 2){
Admin newAdmin = new Admin();
System.out.println("How many admins do you have? ");
int size = console.nextInt();
int[] admins = new int[size];
for(int i = 0; i < admins.length; i++)
{
System.out.println("What is the admin's first name? ");
String firstName = console.next();
newAdmin.setFirstName(firstName);
System.out.println("What is the admin's last name? ");
String lastName = console.next();
newAdmin.setLastName(lastName);
System.out.println("What is their Admin's ID number? ");
double adminId = console.nextDouble();
newAdmin.setAdminId(adminId);
System.out.println("What is the Admin's department? ");
String department = console.next();
newAdmin.setDepartment(department);
System.out.println("What is their salary? ");
int salary = console.nextInt();
newAdmin.setsalary(salary);
}
}
else if (printMenu == 3){
System.out.println("First name: " + newStudent.getFirstName());
System.out.println("Last name: " + newStudent.getLastName());
System.out.println("ID Number: " + newStudent.getStudentID());System.out.println("GPA: " + newStudent.getgrade());System.out.println("Major: "+newStudent.getMajor());
}
else if (printMenu == 4){
System.out.println("First name: " + newAdmin.getFirstName());
System.out.println("Last name: " + newAdmin.getLastName()); System.out.println("ID Number: " + newAdmin.getAdminId()); System.out.println("GPA: " + newAdmin.getgrade());
System.out.println("Major: " + newAdmin.getsalary());
}
else if(printMenu == 5){
System.out.println("Thanks for using my program!");
}
}
}
// This method will bring up the beginning menu for the user
public static void printMenu(){
//Asking the user which option they are selecting
System.out.println("How would you like to input your data?");
System.out.println("1. Enter in students. ");
System.out.println("2. Enter in admins. ");
System.out.println("3. Print the student information. ");
System.out.println("4. Print admin information. ");
System.out.println("5. Exit the program. ");
}
}
For the student grade I need to average there 5 grades together using an array.
public class Student {
// stores the first name
private String firstName;
// stores the last name
private String lastName;
// stores the
private int year;
// stores the grades
private double[] grades;
// stores the ID number
private double studentID;
private String major;
public static int studentInfo;
//here is where it sets the defaults
public Student(){
firstName = "Jane";
lastName = "Doe";
year = 1;
grades = new double[]{0,0,0,0,0};
studentID = 0;
major = "undeclared";
studentInfo++;
}
public static int studentInfo(){
return (studentInfo);
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public double[] getGrades() {
return grades;
}
public void setGrades(double[] grades) {
this.grades = grades;
}
public double getStudentID() {
return studentID;
}
public void setStudentID(double studentID) {
this.studentID = studentID;
}
public String getMajor() {
return major;
}
public void setMajor(String major) {
this.major = major;
}
public static int getStudentInfo() {
return studentInfo;
}
public static void setStudentInfo(int studentInfo) {
Student.studentInfo = studentInfo;
}
public Student(String firstName, String lastName, int year, double[] grades, double studentID){
this.firstName = firstName;
this.lastName = lastName;
this.year = year;
this.grades = grades;
this.studentID = studentID;
studentInfo++;
}
}
I understand how to build it in the class side but I don't understand how to use it in MainEntry. It keeps asking me to change type and I can't figure out what else to do to fix it. I have issues with arrays so that's something that I'm not quite the best at...
Any help is appreciated.
1) For this, you need to declare newStudent outside of the if statement.
while(printMenu != 5){
Student newStudent = null; // ← newStudent is declared here
printMenu();
printMenu = console.nextInt();
This means that you don't declare it later, only assign to it the result of the new operator:
int size;
System.out.println("How many students do you have? ");
size = console.nextInt();
newStudent = new Student(); // ← this is only an assignment, not a declaration
It also means that you have to be careful when the user wants to display the information concerning the student, because newStudent can be null (i.e. no information have been entered yet).
2) The average is not a double array, just a double. This is why the compiler complains about incompatible types. The average will not be computed automatically, you have to do it yourself. Basically, you need two steps. First, iterate through the array and calculate the sum of the elements:
double sum = 0;
for (double g : grades) { // do this for all elements of the array
sum += g; // add the element to the sum
}
Then, the average is the sum divided by the number of elements.
double average = sum / grades.length;
So I have successfully added a list of users with fake bank account information into a text file. Now I need someway to read them back into my program.
For example:
If I entered username - mattsmith
and PIN - 1234
The rest of Matt Smiths back account information would show up in the console, and I want to be able to do things like add money, check balance, and withdraw.
What would be the best way to approach this?
Here is the code that I have so far
ATM CLASS
public class ATM {
public static void main(String[] args) {
// variables
String dash = "-------------------\n";
int accounts = 0;
Bank bank = new Bank();
boolean login = true;
// Scanner
Scanner scanner = new Scanner(System.in);
// Welcome screen
System.out.print(dash);
System.out.print("Welcome to the Bank\n");
System.out.print(dash);
System.out.println("Do you have an account with us? (y/n) ");
String answer = scanner.nextLine();
if (answer.equalsIgnoreCase("y")) {
while (login) {
System.out.println("Username: ");
String lUsername = scanner.nextLine();
System.out.println("PIN: ");
int lPin = scanner.nextInt();
if (lUsername.equals(SampleUser.myUserName)
&& lPin == SampleUser.myPin) {
login = false;
System.out.println("\nLogin successful\n");
}
}
Bank.menu();
} else {
// new user is created
System.out.println("Enter your full name below (e.g. John M. Smith): ");
String name = scanner.nextLine();
System.out.println("Create a username: ");
String userName = scanner.nextLine();
System.out.println("Enter your starting deposit amount: ");
double balance = scanner.nextInt();
System.out.print(dash);
System.out.print("Generating your information...\n");
System.out.print(dash);
int pin = bank.PIN();
String accountNum = bank.accountNum();
User user = new User(name, userName, pin, accountNum, balance);
// new user gets added to the array list
Bank.users.add(user);
System.out.println(user);
}
try {
File file = new File("users.text");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
bw.append(String.valueOf(Bank.users));
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
BANK CLASS
public class Bank {
// Generate a random 16 digit bank account number
public String accountNum() {
int max = 9999;
int min = 1000;
int a1 = (int) (Math.random() * (max - min) + min);
int a2 = (int) (Math.random() * (max - min) + min);
int a3 = (int) (Math.random() * (max - min) + min);
int a4 = (int) (Math.random() * (max - min) + min);
String accountNum = a1 + "-" + a2 + "-" + a3 + "-" + a4;
return accountNum;
}
// Generate a random 4 digit PIN
public int PIN() {
int max = 9999;
int min = 1000;
int PIN = (int) (Math.random() * (max - min) + min);
return PIN;
}
public static void menu() {
while (true) {
System.out.print("\n1"); System.out.print(" - View Balance ");
System.out.print("3"); System.out.print(" - Deposit Money\n");
System.out.print("2"); System.out.print(" - Withdraw Money ");
System.out.print("4"); System.out.print(" - Exit\n\n");
System.out.print("I would like to: \n");
Scanner bscanner = new Scanner(System.in);
int mc = bscanner.nextInt();
if (mc == 1) {
System.out.print("Your current balance is: $" + SampleUser.getMyBalance() + "\n");
} else if (mc == 2) {
System.out.print("Enter withdrawl amount: ");
double wd = bscanner.nextDouble();
SampleUser.myBalance -= wd;
System.out.println("\n$" + SampleUser.getMyBalance() + " is your new account total");
} else if (mc == 3) {
System.out.print("Enter deposit amount: ");
double dp = bscanner.nextDouble();
SampleUser.myBalance += dp;
System.out.println("\n$" + SampleUser.getMyBalance() + " is your new account total");
}
}
}
public static void readFile() {
}
// array list for users
static ArrayList users = new ArrayList(); {
};
}
USER CLASS
public class User implements Serializable{
String name;
String userName;
String accountNum;
int pin;
double balance;
public User (String name, String userName, int pin, String accountNum, double balance) {
this.name = name;
this.userName = userName;
this.accountNum = accountNum;
this.pin = pin;
this.balance = balance;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getAccountNum() {
return accountNum;
}
public void setAccountNum(String accountNum) {
this.accountNum = accountNum;
}
public int getPin() {
return pin;
}
public void setPin(int pin) {
this.pin = pin;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
}
[1] http://prntscr.com/2jqm20
This is what I have to do "Write a java application that prompts for the person ’ s information , instantiates an object of class Health Profile for that person and prints the information from that object — including the person ’ s First name , last name , gender , date of birth , height and weight — then calculates and prints the person ’ s age in years , BMI , maximum heart rate and target - heart - rate range . It should also
display the “ BMI values ” chart from Exercise 2 . 33 ." But I am getting errors whenever I run it.
Here is the code:
import java.util.*;
public class HealthProfile {
String firstName;
String lastName;
char gender;
int BirthMonth;
int BirthDay;
int BirthYear;
int height;
int weight;
public HealthProfile(String fName, String lName, char Genderr, int birthMonth, int birthDay, int birthYear, int heightt, int weightt){
firstName = fName;
lastName = lName;
gender = Genderr;
BirthMonth = birthMonth;
BirthDay = birthDay;
BirthYear = birthYear;
height = heightt;
weight = weightt;
}
HealthProfile() {
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getLastName() {
return lastName;
}
public void setGender(char gender) {
this.gender = gender;
}
public char getGender() {
return gender;
}
public void setBirthMonth(int BirthMonth) {
this.BirthMonth = BirthMonth;
}
public int getBirthMonth() {
return BirthMonth;
}
public void setBirthDay(int BirthDay) {
this.BirthDay = BirthDay;
}
public int getBirthDay() {
return BirthDay;
}
public void setBirthYear(int BirthYear) {
this.BirthYear = BirthYear;
}
public int getBirthYear() {
return BirthYear;
}
public void setHeight(int height) {
this.height = height;
}
public double getHeight() {
return height;
}
public void setWeight(int weight) {
this.weight = weight;
}
public double getWeight() {
return weight;
}
public int Age(){
Calendar now = Calendar.getInstance();
int nowYear = now.get(Calendar.YEAR);
int nowMonth = now.get(Calendar.MONTH);
int nowDay = now.get(Calendar.DATE);
int day = now.get(Calendar.DATE);
int month = now.get(Calendar.MONTH);
int year = now.get(Calendar.YEAR);
if (nowMonth > BirthMonth);
return (nowYear - BirthYear);
}
public double getBMI(){
return (weight * 703)/(height * height);
}
public int MaxHeartRate(){
return 220-Age();
}
public double TargetHeartRate(){
return MaxHeartRate() * 0.85 + MaxHeartRate() * 0.5;
}
}
Here is the test part:
import java.util.Scanner;
public class HealthProfileTest {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String firstName;
String lastName;
String DoB;
String theMonth;
String theDay;
String theYear;
char gender;
int Month;
int Day;
int Year;
double height = 0.0;
double weight;
HealthProfile personalInfo = new HealthProfile();
System.out.println("Enter your first name: ");
firstName = input.nextLine();
System.out.println("Enter your last name: ");
lastName = input.nextLine();
System.out.println("Male or female: ");
gender = input.nextLine().charAt(0);
System.out.println("Enter your date of birth in mm/dd/yyyy format: ");
DoB = input.nextLine();
theMonth = DoB.substring(0,2);
theDay = DoB.substring(3,5);
theYear = DoB.substring(6,10);
Month = Integer.parseInt(theMonth);
Day = Integer.parseInt(theDay);
Year = Integer.parseInt(theYear);
System.out.println("Enter your height in inches: ");
height = input.nextInt();
System.out.println("Enter your weight in pounds: ");
weight = input.nextInt();
System.out.println("Name: " + personalInfo.getFirstName() + personalInfo.getLastName());
System.out.println("Gender: " + personalInfo.getGender());
System.out.println("DoB: " + personalInfo.getBirthMonth() + "/" + personalInfo.getBirthDay() + "/" + personalInfo.getBirthYear());
System.out.println("Height: " + personalInfo.getHeight());
System.out.println("Weight: " + personalInfo.getWeight());
System.out.println("Age: " + personalInfo.Age());
System.out.println("BMI: " + personalInfo.getBMI());
System.out.printf("Max heart rate: ", personalInfo.MaxHeartRate());
System.out.printf("Target heart rate: ", personalInfo.TargetHeartRate());
System.out.println(" ");
System.out.println( "BMI VALUES" );
System.out.println("Underweight: Under 18.5");
System.out.println("Normal: 18.5-24.9 ");
System.out.println("Overweight: 25-29.9");
System.out.println("Obese: 30 or over");
}
}
Here is the output:
Name: nullnull
Gender:
DoB: 0/0/0
Height: 0.0
Weight: 0.0
Age: 2013
Exception in thread "main" java.lang.ArithmeticException: / by zero
at HealthProfile.getBMI(HealthProfile.java:108)
at HealthProfileTest.main(HealthProfileTest.java:43)
Java Result: 1
I know I did everything right but just don't get why it's acting up.
You forgot to call methods setHeight and setWeight. Therefore those values are still 0 by default given that they are numeric primitive types. Obviously the product of 2 zero values equals 0 and dividing then by 0 produces an ArithmeticException
Try calling the methods after accepting the inputs.
System.out.println("Enter your height in inches: ");
height = input.nextInt();
personalInfo.setHeight((int) height);
System.out.println("Enter your weight in pounds: ");
weight = input.nextInt();
personalInfo.setWeight((int) weight);
Similarly set the "Birth" fields
personalInfo.setBirthMonth(Month);
personalInfo.setBirthDay(Day);
personalInfo.setBirthYear(Year);
Aside: Java naming conventions show that variables start with a lowercase letter such as day, month and year. Read about them here
Your exception clearly says Exception in thread "main" java.lang.ArithmeticException: / by zero
As you can see in your own output, height is 0, so when you get the BMI you divide by 0, which is not a legal operation at:
public double getBMI(){
return (weight * 703)/(height * height);
}
Make sure you run your program fully and input a valid height.
Also, as #jlordo pointed out, your code is doing integer division (since all the values involved are integers. This will make you lose anything after the decimal point. Try using:
public double getBMI(){
return ((double)weight * 703)/(height * height);
}
Instead. Casting one of the involved values to a double makes Java keep the decimal values around.
In your following method, change it to something like this:
public double getBMI(){
if(height == 0)
return (weight * 703)/(height * height);
else
return x; // x is whatever the value you want
}