Java - code won't transform dog age in human years - java

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");
}
}
'''

Related

Cannot get names to display from an array using getName

I am currently using java and still haven't got the hang of everything so bear with me. I have been trying to get my names to appear on the output menu but I must be missing something in my code.
Here is my code it has a driver class and client class:
import java.util.Scanner;
//This is TestBaby.java class
public class TestBaby {
// This is main() method, program execution start from here
public static void main(String[] args) {
// This is Scanner class object, it will help to take value from end user
Scanner scan = new Scanner(System.in);
//This is array object of Baby type
Baby[] babies = new Baby[4];
//This is for loop, it iterates 4 times for holding 4 Babies data
for(int i=0; i<4; i++) {
//a. Enter details for each baby (name and age) and thus populate the Baby array
System.out.println("Enter details of " + "Baby " +(i+1));
if(i!=0)
scan.nextLine();
System.out.println("Enter name: ");
String name = scan.nextLine();
System.out.println("Enter age: ");
int age = scan.nextInt();
//This is Baby class object*/
Baby baby = new Baby();
//Set name in Baby class object whatever user entered
baby.setName(name);
//Set age in Baby class object whatever user entered
baby.setAge(age);
//Store current Baby class object into babies array
babies[i] = baby;
}//for end
//b. Output the details of each baby from the array (name and age)
int i=0;
for(Baby baby : babies) {
System.out.println("Baby name: " + baby.getName());
System.out.println("Baby age: " + baby.getAge());
i++;
}
//c. Calculate and display the average age of all babies in the array
double averageAge = averageAge(babies);
System.out.println("Average age of all babies: "+averageAge);
//d. Determine whether any two babies in the array are the same
for(i=0; i<babies.length; i++) {
for(int j=i+1; j<babies.length; j++) {
System.out.println(babies[i].getName()+ " and " + babies[j].getName() + " are equal? " + babies[i].equals(babies[j]));
}//inner for loop
}//outer for loop
}//main() end
//This is averageAge() method, it will calculate average age of Babies
public static double averageAge(Baby[] babies) {
//These are local variables of averageAge() method
int size = babies.length;
double averageAge = 0.0;
//This is for loop, it will calculate total age of babies
for(int i=0; i<size; i++) {
averageAge = averageAge + babies[i].getAge();
}//for end
//return average age to caller of this method
return averageAge/size;
}//averageAge() end
}// TestBaby end
//This is Baby.java class
public class Baby {
//These are instance variable of Baby.java class
private String name;
private int age;
//This is default constructor
public Baby() {
name = "Baby";
age = 1;
}
//This is parameterized constructor will take two parameters, a string to set the name and an integer to set the age
public Baby(String name, int age) {
this.name = name;
this.age = age;
}
//Supply methods for setting the name, setting the age, getting the name and getting the age.
public String getName() {
return name;
}
public void setName(String name) {
//The set method for the name instance variable should ensure that the input is not empty or contain whitespaces (otherwise set a default value)
if (name.trim().isEmpty()){
this.name = "Baby";
this.name = name;
}
}
public int getAge() {
return age;
}
public void setAge(int age) {
//The set method for the age instance variable should validate the input to be between 1 and 4 inclusive (otherwise set a default value).
if (age >= 1 && age <= 4) {
this.age = age;
} //if end
else {
this.age = 1;
}//else end
}// setAge() end
//Give Java code for an equals method for the Baby class.
#Override
public boolean equals(Object obj) {
//This is type casting
Baby baby = (Baby)obj;
//Compare name and age of Baby, if both are same then return true otherwise return false
if(this.age == baby.age && this.name.equalsIgnoreCase(baby.name))
return true;
return false;
}//equals() end
}// Baby end
Please try the code first so you understand what I mean incase its not clear
Baby.setName(String name) only sets the name if name is empty. Your method:
public void setName(String name) {
if (name.trim().isEmpty()){
this.name = "Baby";
this.name = name;
}
}
Try this:
public void setName(String name)
{
if (name == null) ​
​ {
// Use default from constructor
return;
}
String n = name.trim();
if (!n.isEmpty())
​{
​this.name = n;
}
}
I guess your setName() is badly written. You only set the new name if it is empty. I guess there is a not (!) missing.

How can i use input(int) in get and return method in Java?

so im just starting to study java and planning to learn it in-depth and then i wanna ask this thing because im stuck and to learn more.
im trying to use the get and return method.
i wanted to do this in an input way but i cant use the
"int age = person1.GetAge()
System.out.println("Age:" + age) because it will become 2 variables (age)
i hope you understand my question and i know it sounds stupid but i wanna learn xD.
CODE:
//unfinished
//cant use the getAge, no idea how; the value in yrsleft is always 65 despite of the formula that i give
package practice;
import java.util.Scanner;
class person{
String name;
int age;
void speak() {
System.out.print("Hello my name is:" + name);
}
int retire() {
int yrsleft = 65 - age;
return yrsleft;
}
int GetAge() {
return age;
}
}
public class curiosity1{
public static void main(String[]args) {
person person1 = new person();
Scanner input = new Scanner(System.in);
System.out.print("What is your name:");
String name = input.next();
System.out.print("What is your age:");
int age = input.nextInt();
//person1.name = "John";
//person1.age = 30;
System.out.println("Name: " + name);
int age = person1.GetAge();
System.out.println("Age:" + age);
int years = person1.retire();
System.out.println("Years till retirement:" + years);
}
}```
I hope I understood your question correctly, you want to do this?
person1.age = input.nextInt();
person1.name = input.next();
System.out.println("Age:" + person1.getAge());
Or you can override toString() method in your class (since all java classes are inherited from Object, which has this method) to represent your object with a string. Also, you should create a constructor for your Person class.
class Person { // always start class name with a capital letter
int age;
String name;
public Person(int age, String name) {
this.age = age;
this.name = name;
}
// Your methods and etc.
#Override
public String toString() {
return "Name:" + this.name + ". Age:" + this.age;
}
}
And then:
int age = input.nextInt();
String name = input.next();
Person person1 = new Person(age, name);
System.out.println(person1.toString());

How do I compare numbers in Java?

So I wrote code where you enter someone's first name, last name and whatnot and their age. Then someone ele's first name and so on. Then I wanted to compare their ages so I wrote
if (age != age2){
System.out.println (firstName + "is the same age as" + firstName);
}else{
System.out.println ( "They are different ages");
}
}
That tells me that they're the same age which is fine. However, I want to add something where it compares age to age 2 and comes back with "is 22 years older than" and so on. I'm not sure how to do this and I've looked all around and not found things on how to do this.
You may be looking for something like below. You can add conditions accordingly. This is just an example.
public static void main(String[] args){
int ageOne = 22;
int ageTwo = 45;
if((ageOne - ageTwo) == 0){
System.out.print("Person with ageOne and ageTwo are same age");
}else if((ageOne - ageTwo) > 0){
System.out.print("Person with ageOne is " +(ageOne - ageTwo) + " years olders than ageTwo");
}else if((ageOne - ageTwo) < 0){
System.out.print("Person with ageTwo is " +(ageTwo - ageOne) + " years older than ageOne");
}else{
//error condition.
}
}
Java is object oriented language practice in OO.
public class Person {
private String fullName;
private int age;
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
public class ProblemSolution {
public static void main(String[] args) {
Person p1 = new Person();
p1.setAge(18);
p1.setFullName("sunny leone");
Person p2 = new Person();
p2.setFullName("Matty");
p2.setAge(16);
printMessage(p1,p2);
}
private static void printMessage(Person p1, Person p2) {
int a = p1.getAge() - p2.getAge();
if(a < 0) {
System.out.println(p1.getFullName() +" is "+ -(a) +" years younger than "+ p2.getFullName() );
} else if( a > 0) {
System.out.println(p1.getFullName() +" is "+ (a) +" years older than "+ p2.getFullName() );
} else {
System.out.println(p1.getFullName() +" is same age "+ p2.getFullName() );
}
}
}

Incorrect output from user input based on conditional requirements

My program should print out the name and age of all cats with claws who are over 3 years old. For the following input
Enter the name of Cat 1: Sam
Enter the age of Cat 1: 1
Enter the weight of Cat 1: 5
Enter the breed of Cat 1: fluffy1
Does the cat have claws? True or False?: True
Enter the name of Cat 2: Tom
Enter the age of Cat 2: 4
Enter the weight of Cat 2: 5
Enter the breed of Cat 2: fluffy2
Does the cat have claws? True or False?: True
Enter the name of Cat 3: Bob
Enter the age of Cat 3: 5
Enter the weight of Cat 3: 5
Enter the breed of Cat 3: fluffy3
Does the cat have claws? True or False?: False
The output shoud look like this.
The Cats over 3 with claws are:
Name: Tom
Age: 4 Years Old
However, the program finishes with no output. Here is the code I executed.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class MyClass {
private static Cat[] catArray = new Cat[3];
public static void main(String[] args) throws IOException {
for (int i=0;i<3;i++) {
Cat cat = new Cat();
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the Name of Cat " + (i+1) + ": ");
cat.setName(in.readLine());
System.out.print("Enter the Age of Cat " + (i+1) + ": ");
cat.setAge((Integer.parseInt(in.readLine())));
System.out.print("Enter the Weight of Cat " + (i+1) + ": ");
cat.setWeight((Double.parseDouble(in.readLine())));
System.out.print("Enter the Breed of Cat " + (i+1) + ": ");
cat.setBreed(in.readLine());
System.out.print("Does the cat have claws? True or False: ");
String hasClaws = in.readLine();
if(hasClaws.equals("False"))
cat.sethasClaws(false);
else
cat.sethasClaws(true);
catArray[i] = cat;
}
for(int j=0;j<3;j++) {
if((catArray[j].getAge()>=3) && (!catArray[j].hasClaws()) ) {
System.out.println("The cats over 3 with claws are: \n");
System.out.println("Name: " + catArray[j].getName());
System.out.println("Age: " + catArray[j].getAge() + " years old");
}
}
}
}
and also:
public class Cat {
private String name;
private int age;
private double weight;
private String breed;
private boolean hasClaws;
public Cat() {}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public String getBreed() {
return breed;
}
public void setBreed(String breed) {
this.breed = breed;
}
public boolean hasClaws() {
return hasClaws;
}
public void sethasClaws(boolean hasClaws) {
this.hasClaws = hasClaws;
}
}
I believe that the ! operator in (catArray[j].getAge()>=3) && (!catArray[j].hasClaws()) is messing you up. This equates to "show me all cats 3 or over, that don't have claws".
from: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/opsummary.html
! Logical complement operator;
inverts the value of a boolean
Try this:
for(int j=0;j<3;j++) {
if((catArray[j].getAge()>=3) && (catArray[j].hasClaws()) ) {
System.out.println("The cats over 3 with claws are: \n");
System.out.println("Name: " + catArray[j].getName());
System.out.println("Age: " + catArray[j].getAge() + " years old");
}
}

Having issues with the output

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
}

Categories

Resources