In: Computer Science
(USING JAVA)
Implement a class Moth that models a moth flying along a straight line. The moth has a position which is the distance from a fixed origin. When the moth moves toward a point of light its new position is halfway between its old position and the position of the light source. Supply a constructor
public Moth(double initialPosition)
and methods
public void moveToLight(double lightPosition)
public double getPosition()
Explanation of the code is explained in the comments of he code itself.
Code--
import java.util.*;
class Moth
{
private double initialPosition;
//constructor
public Moth(double initialPosition)
{
this.initialPosition=initialPosition;
}
//required method
public void moveToLight(double lightPosition)
{
initialPosition=(initialPosition+lightPosition)/2;
}
//getter
public double getPosition()
{
return initialPosition;
}
}
public class Main
{
public static void main(String[] args)
{
//create an object of Moth
Moth myMoth=new Moth(66.6);
//display the current position
System.out.println("Initial position of moth = "+
myMoth.getPosition());
//call moveToLight
myMoth.moveToLight(22.6);
//Display the new pisition
System.out.println("New position of moth = "+
myMoth.getPosition());
}
}
Code Screenshot--
Output Screenshot--
Note--
Please upvote if you like the effort.