Home > Blockchain >  how to create two class methods and using the first class methods variables on an if statement on th
how to create two class methods and using the first class methods variables on an if statement on th

Time:09-30

So I'm trying to create a program that displays the dinosaurs era which it lived in and other stuff but I'm currently stuck on the age.

Here is the question:

setTimePeriod (method) – takes one int parameter representing how many millions of years ago the dinosaur lived and does not return anything; sets the time period instance variable to the middle of the time period. See below for more information

getTimePeriod (method) – takes no parameters; returns a String containing one of “Triassic”, “Jurassic”, or “Cretaceous”. Use the time period instance variable to figure out the time period. Setting the Time period

Recall the Mesozoic Era, when the dinosaurs lived, is divided into three time periods

Triassic (roughly 252 to 201 million years ago)
Jurassic (roughly 201 to 145 million years ago)
Cretaceous (145 to 66 million years ago)

Set the instance variable for the time period to the middle of the time period.

This gives the following numbers

Triassic Period is set to 227
Jurassic Period is set to 173
Cretaceous Period is set to 106

here is what I wrote:

public String getTimePeriod()
{
    if (Triassic > 201 && Triassic < 252)
    {
        return "Triassic period";
    }
    
    if (Jurrasic > 145 && Jurrasic <201)
    {
        return "Jurrasic period";
    }
    
    if (Cretaceous > 66 && Cretaceous < 145)
    {
        return "Cretaceous period";
    }
}
// Returns a String representing which
// period the dinosuar lived in
// based on the value of the time period instance variable


// setTimePeriod

public int setTimePeriod(int age)
{
     int Triassic = 227;
     int Jurrasic = 173;
     int Cretaceous = 106;
}

Can anyone tell me what to do?

CodePudding user response:

I advise you to repeat about encapsulation in Java.

All conditions of this task is hard to understand, so this is my way to solve this problem:

public class Dinosauros {

    private String namePeriod;

    private int timePeriod;

    public void setTimePeriod(int age) {
        if (age < 252 && age > 201) {
            this.timePeriod = 227;
        } else if (age < 201 && age > 145) {
            this.timePeriod = 173;
        } else if (age < 145 && age > 66) {
            this.timePeriod = 106;
        } else {
            System.out.println("Enter correct time period.");
        }
    }
    
public String getNamePeriod() {
        if (timePeriod == 227) this.namePeriod = "Triassic";
        else if (timePeriod == 173) this.namePeriod = "Jurassic";
        else if (timePeriod == 106) this.namePeriod = "Cretaceous";
        return namePeriod;
    }
}
    
  • Related