Write a JAVA program that repeatedly prompts your user for a number, uses a recursive function to calculate the product of that number times three (3), and displays the product. Select a sentinel value that allows your user to quit. Do NOT use the multiplication operator (*) in your proposed solution.

Respuesta :

Answer:

// Scanner class is imported to receive user input

import java.util.Scanner;

// class Solution is defined  

public class Solution{

   // recursive function to calculate  

   // multiplication of two numbers

   // the second number is initialised to 3

   // it return the product

   public static int product(int x, int y)

   {

       // first it check if 3 is not 0

       // then it uses repetitive addition to get the product

       // it continues till 3 becomes 0

       if (y != 0)

           return (x + product(x, y - 1));

   }

     

   // main method to begin program execution

   public static void main (String[] args)

   {

       // Scanner object scan is initialize to receive input

       // via keyboard

       Scanner scan = new Scanner(System.in);

       // prompt is display to user to enter number

       System.out.println("Enter your number to multiply: ");

       // user input is assigned to x

       int x = scan.nextInt();

       // 3 is assigned to y which specify the number of times to multiply

       int y = 3;

       // while loop that continue to receive user input as long as it is not -1

       while(x != -1){

           // The result of the product is displayed

           System.out.println(product(x, y));

           // prompt is display to user to enter number

           System.out.println("Enter your number to multiply: ");

           // user input is assigned to x

           x = scan.nextInt();

       }

       

   }

}

Explanation:

The program is written in Java. An image of program output when the code is executed is attached.

A Scanner class is imported that allow program to read input. Then the product method is defined that compute the product of a number3 times using repetitive addition.

Then the method product is called inside the main method where the user is asked to continue input a number as long as the sentinel value (-1) is not entered.

Ver imagen ibnahmadbello