Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

1) Write a program that has an Asteroid class. The class has private data member

ID: 3772368 • Letter: 1

Question

1) Write a program that has an Asteroid class. The class has private data members of size and speed. It has set functions for the size and speed data members. The class also has a displayStats function that outputs the size and the speed. The main should create two asteroids. Once they are created, set the asteroids values. Have Asteroid 1 and size 1 but speed 20 and Asteroid 2 be size 4 and speed 3. Then, call displayStats on each asteroid.

Example execution:

Asteroid: has size of 1 speed of 20

Asteroid: has size of 4 speed of 3

Also, in the final example in the lecture notes, setSize was modified to check if main was trying to change the size greater than 20. Modify setSize again to also check to see if the size is less than one. If it is, set it to one and output a message that the size was too small.

Explanation / Answer

Answer:

Asteroid.java


public class Asteroid {
  
   private int size;
   private int speed;
  
   public void setSize(int sz)
   {
       size = sz;
   }
  
   public void setSpeed(int sp)
   {
       speed = sp;
   }
  
   public void displayStat(Asteroid aa)
   {
       System.out.println("Asteroid: has size of "+ aa.size +" speed of " + aa.speed);
   }

}

MainFunction.java

public class MainFunction {

  
   public static void main(String[] args) {

       Asteroid a = new Asteroid();
       Asteroid b = new Asteroid();
      
       a.setSize(1);
       a.setSpeed(20);
      
       b.setSize(4);
       b.setSpeed(40);
      
       a.displayStat(a);
       b.displayStat(b);
      
      
      
   }

}

OUTPUT:

Asteroid: has size of 1 speed of 20
Asteroid: has size of 4 speed of 40

Modified Asteroid.java for checking the size <1

public class Asteroid {
  
   private int size;
   private int speed;
  
   public void setSize(int sz)
   {
       if(sz <1)
       {
           System.out.println("Size is very Small");
       size = 1;
       }
       else
       size = sz;
   }
  
   public void setSpeed(int sp)
   {
       speed = sp;
   }
  
   public void displayStat(Asteroid aa)
   {
       System.out.println("Asteroid: has size of "+ aa.size +" speed of " + aa.speed);
   }

}

OUTPUT:

Size is very Small
Asteroid: has size of 1 speed of 20
Asteroid: has size of 4 speed of 40