Westonci.ca is the best place to get answers to your questions, provided by a community of experienced and knowledgeable experts. Get immediate answers to your questions from a wide network of experienced professionals on our Q&A platform. Get precise and detailed answers to your questions from a knowledgeable community of experts on our Q&A platform.
Sagot :
Answer:
Following are the constructor to the given code:
Bug(int position) //defining a constructor that defines a integer parameters
{
this.position = position;//use this key word to hold parameter value
right = true;//defining a variable right that hold a boolean value
}
Explanation:
In this code, a constructor is declared that defines integer parameters with it, Inside the constructor, this keyword is used to holds the "position" parameter value and defines a boolean variable "right" that holds a boolean value.
Full program:
public class Bug //declaring a class Bug
{
private int position;//declaring integer variable position
private boolean right;//declaring boolean variable
public Bug(int position) //defining a parameterized constructor
{
this.position = position;//use this to hold position value
right = true;//holding boolean value
}
public void turn() //defining a method turn
{
right = !right;//holding value
}
public void move() //defining method move
{
if(right)//use if to check boolean value
{
position++;//incrementing position value
}
else//else block
{
position--;//decreasing position value
}
}
public int getPosition()//defining method getPosition
{
return position;//return position value
}
public static void main(String[] args) //main method
{
Bug bug = new Bug(10);//creating class object
System.out.println("Expected = 10, Actual = " + bug.getPosition());//calling method with printing value
bug.move();//calling method
System.out.println("Expected = 11, Actual = " + bug.getPosition());//calling method with printing value
bug.move();//calling method
bug.move();//calling method
bug.move();//calling method
System.out.println("Expected = 14, Actual = " + bug.getPosition());//calling method with printing value
bug.turn();//calling method
bug.move();//calling method
bug.move();//calling method
System.out.println("Expected = 12, Actual = " + bug.getPosition());//calling method with printing value
bug.turn();//calling method
bug.move();//calling method
System.out.println("Expected = 13, Actual = " + bug.getPosition());//calling method with printing value
}
}
Output:
Please find the attached file.
We appreciate your time. Please revisit us for more reliable answers to any questions you may have. Your visit means a lot to us. Don't hesitate to return for more reliable answers to any questions you may have. Discover more at Westonci.ca. Return for the latest expert answers and updates on various topics.