Create a class called Planet Store as fields the name of the
Create a class called Planet. Store as fields the name of the planet, the gravity, and the length of the year. Create the appropriate constructors and accessors and toString. Build an array of this class. Create a program that displays the data on a planet based on user choice. For example, if the person selected Mars, then 3.71 m/s2 and 686 days
Solution
Hi buddy, please find the below java program
import java.util.*;
import java.lang.*;
import java.io.*;
class Planet{
private String name;
private double gravity;
private int days;
//Default Constructor
public Planet(){
}
//Parameterized constructor
public Planet(String name, double gravity, int days){
this.name = name;
this.gravity = gravity;
this.days = days;
}
//Setter methods
public void setName(String name){
this.name = name;
}
public void setGravity(double gravity){
this.gravity = gravity;
}
public void setDays(int days){
this.days = days;
}
//Getter methods
public String getName(){
return this.name;
}
public double getGravity(){
return this.gravity;
}
public int getDays(){
return this.days;
}
//To String method
@Override
public String toString(){
return name+\" \"+gravity+\"m/s2 \"+days;
}
}
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
// Array of 5 planets
Planet planets[] = new Planet[5];
planets[0] = new Planet(\"Mercury\",3.7,88);
planets[1] = new Planet();
planets[1].setName(\"Venus\");
planets[1].setGravity(8.87);
planets[1].setDays(225);
planets[2] = new Planet(\"Earth\",9.807,365);
planets[3] = new Planet(\"Mars\",3.711,687);
planets[4] = new Planet(\"Jupiter\",24.79,4380);
System.out.println(\"Enter the name of the planet\");
String name = new Scanner(System.in).next();
for(int i=0;i<planets.length;i++){
if(planets[i].getName().equals(name)){
System.out.println(planets[i]);
}
}
}
}
OUTPUT :
Enter the name of the planet
Venus
Venus 8.87m/s2 225

