Hello! I am trying to finish this Recursive multiplication program and I am stuck. What I need to do is write a recursive function that accepts two arguments into the parameters x and y. The function should return the value of x times y. I used this program from the book as an example:
import javax.swing.JOptionPane;
/**
This program will demonstrate the recursive
factorial method
*/
public class FactorialDemo
{
public static void main(String[]args)
{
String input; // To hold user input
int number; // To hold a number
// Get a number from the user.
input = JOptionPane.showInputDialog("Enter a " + "nonnegative integer:");
number = Integer.parseInt(input);
// display the factorial of the number.
JOptionPane.showMessageDialog(null, "Result is " + factorial(number));
System.exit(0);
}
/**
The factorial method uses recursion to calculate
the factorial of its argument, which is assumed
to be a nonnegative number.
@param n the number to use in the calculation.
@return the factorial of n.
*/
private static int factorial(int a)
{
if (a == 0)
{
return 1;
}
else
{
return a * factorial(a - 1);
}
}
}
I then, modified it to the assignment but now I get this error message:
RecursiveMultiplication.java:25: multiplication(int,int) in RecursiveMultiplication cannot be applied to (int)
JOptionPane.showMessageDialog(null, "Result is " + multiplication(number));
What am I doing wrong?
Here's my program:
import javax.swing.JOptionPane;
/**
This program will demonstrate the recursive
factorial method
*/
public class RecursiveMultiplication
{
public static void main(String[]args)
{
String input; // To hold user input
int number; // To hold a number
// Get a number from the user.
input = JOptionPane.showInputDialog("Enter a " + "nonnegative integer:");
number = Integer.parseInt(input);
input = JOptionPane.showInputDialog("Enter a " + "nonnegative integer: to multiply against the first one:");
number = Integer.parseInt(input);
// display the factorial of the number.
JOptionPane.showMessageDialog(null, "Result is " + multiplication(number));
System.exit(0);
}
/**
The factorial method uses recursion to calculate
the factorial of its argument, which is assumed
to be a nonnegative number.
@param n the number to use in the calculation.
@return the factorial of n.
*/
private static int multiplication(int a, int b)
{
if (a == 0)
{
return 0;
}
else
{
if (b == 0)
{
return 0;
}
else
{
return a + multiplication(a, b - 1);
}
}
}
}