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
}
Related
I tried a for loop with an if in it but I didn't know what I should've put in if(?), so then I went for using try and a catch and imported InputMismatchException. I then tried making an array with numbers from 0 to 9(I am a noob and don't know what I am doing) and used a for loop with and if, I know I could use a while. Please help me recent them from entering a string instead of numbers.
import java.util.Scanner;
import java.util.Arrays;
import java.util.InputMismatchException;
public class Employee {
// fields
private String firstName, lastName;// creates both firstName and lastName as string and private fields
private String sal;// creates sal a private and double field
private int years;// creates years a private and int field
// constructors
public Employee() {// default constructor
this("", "", 0, 0);// this sets the default values for each one of the fields
}
public Employee(String firstName, String lastName, double sal, int years) {// overloaded constructor
this.firstName = firstName;// gets the values from the field firstname and then puts it in string firstname
this.lastName = lastName;// gets the value from the field secondname and then puts it in string
// secondname
this.sal = sal;// gets the value from the field sal and then puts it in float sal
this.years = years;// gets the value from the field years and then puts it in int years
}
// methods
public String getFirstName() {// accessor for the field firstname
return firstName;
}
public void setFirstName(String firstName) {// mutator for the field firstname
this.firstName = firstName;
}
public String getLastName() {// accessor for the field lastname
return lastName;
}
public void setLastName(String lastName) {// mutator for the field lastname
this.lastName = lastName;
}
public String getSal() {// accessor for the field lastname
return sal;
}
public void setSal(String sal) {// mutator for the field sal
this.sal = sal;
}
public int getYears() {// accessor for the field years
return years;
}
public void setYears(int years) {// mutator for the field years
this.years = years;
}
public void ScannerMethod() {
int arrInt[] = new int[10];
arrInt[0] = 0;
int j = 0;
boolean a = false;
Scanner get = new Scanner(System.in);
System.out.println("enter first name: ");
firstName = get.next();
System.out.println("enter second name: ");
lastName = get.next();
System.out.println("enter the salary: ");
while(j<10) {
arrInt[j] = j+1;
j++;
}
for(int i = 0; i<1; i++){
if(sal == arrInt[]){
System.out.println("Pleas enter it agian: ");
sal = get.next();
i = 0;
}else{
i = 2;
}
}
/*/while (!a) {
try {
sal = get.nextDouble();
a = false;
} catch (Exception e) {
System.out.println("Invalid input please enter a numeric value: ");
a = true;
}
}/*/
System.out.println("enter the years of service: ");
years = get.nextInt();
}
public String typeStats() {// this method prints out the stats for the employee
System.out.println("Report: " + firstName.substring(0, 1).toUpperCase() + firstName.substring(1) + " "
+ lastName.substring(0, 1).toUpperCase() + lastName.substring(1) + " $" + sal + " " + years);
return null ;
}
}
Here is a method which asks the user for a double until they input a valid double.
package test2134235;
import java.util.Scanner;
public class ParseDouble {
public static void main(String[] args) {
System.out.println("This is your double: " + getDoubleFromKeyboard());
}
static Double getDoubleFromKeyboard() {
Scanner scanner = new Scanner(System.in);
for (;;) {
System.out.println("input a Double value");
try {
String input = scanner.nextLine();
Double d = Double.parseDouble(input);
return d;
} catch (NumberFormatException e) {
System.out.println("Sorry, only Double values can be used.");
}
}
}
}
You have a comment and an answer that I think address your needs. I wanted to literally answer the question implied in your header: "Trying to stop the user from entering a String into my double in java"
The answer is you can't control what the user types in to the console. What is typed into the console is always going to be characters and read in as a String. It's your job (as the comment and the answer address) to make sure bad input doesn't crash your program. So you need to analyze it and ask "Does this look like it's a double?" and if it does, go ahead and store it in your variable and if not, take some other action like prompting the user to try again.
I am trying to do a program that will convert the input age of a dog into human years, but it doesn't work. Here are the instructions I had for the conversion of the dog years to human years:
A method inHumanYears which will return the age of a pet dog in human years. Here is how to calculate it:
15 human years equals the first year of a medium-sized dog's life.
Year two for a dog equals about nine years for a human.
And after that, each human year would be approximately five years for a dog.
Here a few examples:
a 4-month old dog = 0.25 (which is 1/4 of a year)*15 = 3.75 human years
a 5 years old = 15+9+(5-2) * 5 = 39 human years
So here is what my code looks so far:
import java.util.Scanner;
public class MyPet_1_lab7 {
// Implement the class MyPet_1 so that it contains 3 instance variables
private String breed;
private String name;
private int age;
private double inHumanYears;
// Default constructor
public MyPet_1_lab7()
{
this.breed = null;
this.name = null;
this.age = 0;
}
// Constructor with 3 parameters
public MyPet_1_lab7(String a_breed, String a_name, int an_age){
this.breed = a_breed;
this.name = a_name;
this.age = an_age;
this.inHumanYears = inHumanYears();
}
// Accessor methods for each instance variable
public String getBreed(){
return this.breed;
}
public String getName(){
return this.name;
}
public int getAge(){
return this.age;
}
//Mutator methods for each instance variable
public void setBreed(String a_breed){
this.breed = a_breed;
}
public void setName(String a_name){
this.name = a_name;
}
public void setAge(int an_age){
this.age = an_age;
this.inHumanYears = inHumanYears();
}
// toString method that will return the data in an object formated as per the output
public String toString(){
return (this.breed + " whose name is " + this.name + " and " + (double)this.age + " dog years (" + inHumanYears() + " human years old)");
}
public boolean equals(MyPet_1_lab7 a){
if ((this.breed.equals(a.getBreed())) && (this.age == a.getAge())){
return true;
}
else
return false;
}
public double inHumanYears(){
if ((double)age >= 2 ){
inHumanYears = (15 + 9 + (age - 2))*5;
return (inHumanYears);
}
else {
inHumanYears = age*15;
return (inHumanYears);
}
}
public double getHumanYears(){
double yearOneAge = age >=1 ? 1.0: age;
double yearTwoAge = age >=2 ? 1.0: age > 1? age-1.0: 0.0;
double yearThreeAge = age > 2 ? age-2.0: 0.0;
inHumanYears = yearOneAge * 15 + yearTwoAge*9 + yearThreeAge * 5;
return inHumanYears;
}
public static void main(String[] args) {
Scanner keyboard = new Scanner (System.in);
System.out.print("What type of dog do you have? ");
String breed = keyboard.nextLine();
System.out.print("What is its name? ");
String name = keyboard.nextLine();
System.out.print("How old? ");
int age = keyboard.nextInt();
MyPet_1_lab7 dog= new MyPet_1_lab7();
System.out.println(dog);
MyPet_1_lab7 dog1 = new MyPet_1_lab7(breed,name,age);
System.out.println(dog1);
}
}
'''
The issue is your toString() method accesses a field you set with a method that has not been called. This
public String toString(){
return (this.breed + " whose name is " + this.name + " and "
+ this.age + " dog years (" + inHumanYears + " human years old)");
}
should be changed to invoke inHumanYears(). Like,
public String toString(){
return (this.breed + " whose name is " + this.name + " and "
+ this.age + " dog years (" + inHumanYears() + " human years old)");
}
Your method InHumanYears() is never called + your attribute inHumanYears is never assigned.
You must change your second constructor.
Before :
public MyPet_1_lab7(String a_breed, String a_name, int an_age){
this.breed = a_breed;
this.name = a_name;
this.age = an_age;
}
After :
public MyPet_1_lab7(String a_breed, String a_name, int an_age){
this.breed = a_breed;
this.name = a_name;
this.age = an_age;
this.inHumanYears = inHumanYears();
}
You must also called inHumanYears() in setAge() :
setAge(int age){
this.age = age;
this.inHumanYears = inHumanYears();
}
I obtain this execution (I think your calculation is incorrect):
toto whose name is tata and 3 dog years (125.0 human years old)
your algo seems wrong for the stated requirements.
15 human years equals the first year of a medium-sized dog's life.
Year two for a dog equals about nine years for a human.
And after that, each human year would be approximately five years
for a dog.
also you should change age to allow for decimal points. (if not age may be in months, like the example for your 4month old dog -> in which case you should divide everything by 12). It's usually better to name it ageMonth or ageYear to remove that ambiguity.
you can try breaking each component down.
note: the ?: are ternary operators. Think of it as a "short form" for the if-else statement
public double getHumanYears(){
double yearOneAge = age>=1 ? 1.0: age;
//if age>1, then year1Age=1, otherwise year1Age = age
double yearTwoAge = age>=2 ? 1.0: age>1? age-1.0: 0.0;
//if age>2, then year2Age=2, elseIf age>1, then year2Age = age-1, otherwise, year2Age is 0.
double yearThreeAge = age>2 ? age-2.0: 0.0;
//if age>2, then year3Age= age-2, otherwise, year3Age is 0.
//the formula will break down an age into 3 parts.
//yearOneAge: from 0.0 to 1.0.
//yearTwoAge: from 0.0 to 1.0.
//yearThreeAge: from 0.0 onwards.
//e.g. age=0.8years, year1=0.8, year2=0.0, year3=0.0
//e.g. age=1.5years, year1=1.0, year2=0.5, year3=0.0
//e.g. age=3.6years, year1=1.0, year2=1.0, year3=1.6
inHumanYears = yearOneAge * 15 + yearTwoAge * 9 + yearThreeAge * 5
return inHumanYears;
}
also like Quentin said, you forgot to call getHumanYears in your setter and constructor, or you can update the toString to call getHumanYears().
Ok, so thank you everybody for your time and your help. So here is what I did, I changed the private int age to a double. My friend told me that we didn't need to necessarily put it to an integer. The rest was just change everything to double and it solved all my problem for my output:
import java.util.Scanner;
public class MyPet_1_lab7 {
// Implement the class MyPet_1 so that it contains 3 instance variables
private String breed;
private String name;
private double age; // instead of private int age;
MyPet_1_lab7 dog1;
MyPet_1_lab7 dog2;
// Default constructor
public MyPet_1_lab7()
{
this.breed = null;
this.name = null;
this.age = 0;
}
// Constructor with 3 parameters
public MyPet_1_lab7(String a_breed, String a_name, double an_age){
this.breed = a_breed;
this.name = a_name;
this.age = an_age;
}
// Accessor methods for each instance variable
public String getBreed(){
return this.breed;
}
public String getName(){
return this.name;
}
public double getAge(){
return this.age;
}
//Mutator methods for each instance variable
public void setBreed(String breed2){
this.breed = breed2;
}
public void setName(String name2){
this.name = name2;
}
public void setAge(double age2){
this.age = age2;
}
// toString method that will return the data in an object formated as per the output
public String toString(){
return (this.breed + " whose name is " + this.name + " and " + this.age + " dog years (" + inHumanYears() + " human years old)");
}
public boolean equals(MyPet_1_lab7 a){
if ((this.breed.equals(a.getBreed())) && (this.age == a.getAge())){
return true;
}
else
return false;
}
double human_age = 0;
public double inHumanYears(){
if (this.age < 1)
human_age = (this.age) * 15;
if (this.age >=1 && this.age < 2)
human_age = 15 + (this.age - 1) * 9;
if (this.age >= 2 ){
human_age = 15 + 9 + (age - 2)*5;
}
return human_age;
}
public static void main(String[] args) {
Scanner keyboard = new Scanner (System.in);
System.out.print("What type of dog do you have? ");
String breed = keyboard.nextLine();
System.out.print("What is its name? ");
String name = keyboard.nextLine();
System.out.print("How old? ");
double age = keyboard.nextDouble();
MyPet_1_lab7 dog= new MyPet_1_lab7();
System.out.println(dog);
MyPet_1_lab7 dog1 = new MyPet_1_lab7(breed,name,age);
System.out.println(dog1);
Scanner key = new Scanner(System.in);
System.out.println("\nLet's set up the 1st dog ... ");
System.out.print("\tWhat breed is it? ");
String breed1 = key.nextLine();
System.out.print("\tWhat is the dog's name? ");
String name1 = key.nextLine();
System.out.print("\tHow old is the dog in dog years (a double number)? ");
double age1 = key.nextDouble();
MyPet_1_lab7 dog2 = new MyPet_1_lab7 (breed1, name1, age1);
System.out.println("Dog1 is now a(n) " + dog2);
System.out.println("\nAre the 2 dogs the same breed and age?");
if ((breed.equals(breed1))&& age == age1)
System.out.println("Yes, they are the same breed and age");
else
System.out.println("No, they are not the same breed and/or age");
}
}
'''
For some reason when I input values for RTH and CTH I receive 0.0 values. I had a similar issue on my shift getters, but I managed to fix that. Unfortunately, attempting to reverse engineer the problem hasn't helped. I've provided the code for my class and my driver, although I am almost convinced the issue is somewhere in the class. Nevertheless, can anyone take a quick look at the RTH / CTH setters/ getters and see what I've done wrong in setting or calling them.
public class TeamLeader extends ProductionWorker
{
//private variables
private double RTH;
private double CTH;
private double payRate;
private double monthlyBonus;
//constructor
public TeamLeader(String name, String number, String hd, int shift,
double rate, double monthlyBonus, double RTH, double CTH)
{
super(name, number, hd, shift, rate);
this.monthlyBonus = monthlyBonus;
}
public void setmonthlyBonus(double monthlyBonus)
{
this.monthlyBonus = monthlyBonus;
}
public void setpayRate(double payRate)
{
this.payRate = payRate;
}
public void setRTH(double r)
{
RTH = r;
}
public void setCTH(double c)
{
CTH = c;
}
//Getters
public double getmonthlyBonus()
{
return monthlyBonus;
}
public double getpayRate()
{
return payRate;
}
public double getRTH()
{
return RTH;
}
public double getCTH()
{
return CTH;
}
}
Driver
public class WorkDriver {
public static void main(String[] args) {
String name;
String number;
String hireDate;
int shift;
double payRate;
double monthlyBonus;
double RTH;
double CTH;
name = JOptionPane.showInputDialog("Enter your name");
number = JOptionPane.showInputDialog
("Enter your number (Format: XXX-L)");
hireDate = JOptionPane.showInputDialog("Enter your hire date");
shift = Integer.parseInt(JOptionPane.showInputDialog
("Please enter the work shift for the employee:\n"
+ "\tEnter 1 for the day shift"
+ "\n\tEnter 2 for the night shift"));
payRate = Double.parseDouble(JOptionPane.showInputDialog
("Enter your pay rate"));
monthlyBonus = Double.parseDouble(JOptionPane.showInputDialog
("Enter your monthly bonus"));
RTH = Double.parseDouble(JOptionPane.showInputDialog
("Enter your required traing hours"));
CTH = Double.parseDouble(JOptionPane.showInputDialog
("Enter your training hours attended"));
//Production worker object
TeamLeader driver = new TeamLeader(name, number,
hireDate, shift, payRate, monthlyBonus, RTH, CTH);
JOptionPane.showMessageDialog(null,
"----------- Employe Info ----------------"
+ "\nName: " + driver.getName()
+ "\nEmployee Number: " + driver.getNumber()
+ "\nHire Date: " + driver.getHireDate()
+ "\nPay Rate: " + driver.getPayRate()
+ "\nShift: " + driver.getShift()
+ "\nMonthly Bonus: " + driver.getmonthlyBonus()
+ "\nRequired Training Hours: " + driver.getRTH()
+ "\nTraining Hours Attended: " + driver.getCTH());
System.exit(0);
}
}
You never call the setters of CTH and RTH. You pass their values to your constructor but don't use them.
Add to your constructor setting of CTH and RTH :
public TeamLeader(String name, String number, String hd, int shift,
double rate, double monthlyBonus, double RTH, double CTH)
{
super(name, number, hd, shift, rate);
this.monthlyBonus = monthlyBonus;
this.RTH = RTH;
this.CTH = CTH;
}
You're calling the parent (super) constructor, but it doesn't take RTH or CTH, and you never set RTH and CTH on your TeamLeader object.
public TeamLeader(String name, String number, String hd, int shift,
double rate, double monthlyBonus, double RTH, double CTH)
{
super(name, number, hd, shift, rate);
this.monthlyBonus = monthlyBonus;
this.RTH = RTH;
this.CTH = CTH;
}
You are not setting the passed RTH to the instance's RTH. See code above for the fix
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;
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());