...

View Full Version : need to modify this method



Bob42
02-06-2008, 01:22 AM
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.



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;
}
}
}

Aradon
02-06-2008, 01:30 AM
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



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)

Bob42
02-06-2008, 03:15 AM
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.


result = a + mystery(a, Math.abs(b) - 1);

I'm stuck on the last part though.

shyam
02-06-2008, 06:16 AM
return (b < 0) ? -result : result;



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum