Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

# Thread: need to modify this method

1. ## need to modify this method

I have a program that I'm working on. What it does is take 2 integers and multiplies them together. The problem is that if the second integer is negative, a bunch of errors are displayed. I need to modify this method so that the second integer can be a negative number, but that's what I'm stuck on. I'm hoping that someone can lead me into the right direction.

Code:
```import javax.swing.JOptionPane;  // import class JOptionPane

public class App0644 {
public static void main(String[] args)
{
int x;
int y;
int result;

x = Integer.parseInt( JOptionPane.showInputDialog("Enter first integer:"));
y = Integer.parseInt( JOptionPane.showInputDialog("Enter second integer:"));
result = mystery(x, y);

System.out.println("Result: "+result);

System.exit(0);  // terminate application with window
}

public static int mystery(int a, int b)
{
if (b == 1)
return a;
else
{
int result = 0;
result = a + mystery(a, b - 1);
return result;
}
}
}```

• You could always take the absolute value of b, and then at the end multiply a negative to the number.

Or you could check to see if the number is negative, and if it is, do calls upward rather then backwards.

That is, when you know that b is negative do

Code:
`result = a + mystery(a, b + 1);`
Instead of the - 1. That way you would still multiply the right number of times. The only trick, of course, is that you'd have to make the result negative at the end (since a positive times a negative is negative)

You could always take the absolute value of b, and then at the end multiply a negative to the number.
Well, I got half of that to work. I'm able to enter a negative integer, but it always displays a positive result even when I do something like 10* -5.

Code:
`result = a + mystery(a, Math.abs(b) - 1);`
I'm stuck on the last part though.

• Code:
`return (b < 0) ? -result : result;`

•

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•