DevX Home Today's Headlines   Articles Archive   Tip Bank   Forums

1. Registered User
Join Date
Oct 2005
Posts
2

## How to create a multiplier using the add function

I am creating a program that will allow the user to input two numbers. What I want to do is multiply the two numbers together however I want to use the add function. for example if they input 5 and 3 i want the program to take 5+5+5=15 instead of taking 5*3. This is what I came up with but I know its wrong. Can anyone get me on the right track?

String firstStr=JOptionPane.showInputDialog("Enter an Integer");
int x=Integer.parseInt(firstStr);
String secondStr=JOptionPane.showInputDialog("Enter a second Integer");
int y=Integer.parseInt(secondStr);

int number=1;
for (number=1;number>y;number++){x=x+x;}
System.out.println(x);

2. Registered User
Join Date
Sep 2005
Location
istanbul / Turkey
Posts
133
x = 5
y = 3

your loop will produce this : ( look at the note )
step 1 : x=x+x ---> x = 5 + 5 -> x = 10 ( you lost original x)
step 2 : x=x+x ---> x = 10 + 10 -> x = 20
step 3 : x=x+x ---> x = 20 + 20 -> x = 40

use another variable to hold the first value of x
or use another variable to hold the sum.

note : number > y or number <= y ?
Last edited by mr1yh1; 11-01-2005 at 06:33 AM.

3. ## Extended version:

Code:
```public class CountAdder {
}
/**
* Get user integer input, don't stop until it's correct
* @param prompt
* @return
*/
private int getUserInt(String prompt) {
while (true) {
String s = JOptionPane.showInputDialog(prompt);
try {
return Integer.parseInt(s);
}
catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(null, s + " is not an integer",
"Input error", JOptionPane.ERROR_MESSAGE);
}
}
}
public void doMultiplication() {
int x=getUserInt("Enter an Integer");
int y=getUserInt("Enter a second Integer");

int total=0;
for (int i=0; i<y; i++) {
total += x;
}
System.out.println(total);
}
/**
* Make an instance of class, then invoke the instance method(s).
* @param args
*/
public static void main(String[] args) {
cA.doMultiplication();
}

}```

#### Posting Permissions

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

 FAQ Latest Articles Java .NET XML Database Enterprise