Reputation: 155
I'm writing class where I'm generating 2 random numbers a and b (between 1 to 100) and I want to keep generating those 2 numbers until a+b=20 and a*b=100 (both conditions must be true). when both conditions satisfied, I want to print a and b and also the numbers of tries it took to satisfy those conditions.
Here is my code
public class App {
public static void main(String[] args) throws Exception {
int a = 0;
int b = 0;
int add;
int multi;
int i=0;
Random r = new Random();
do{
a = r.nextInt(99)+1;
b = r.nextInt(99)+1;
add = a+b;
multi = a*b;
i++;
System.out.println("iteration number : " +i);
}
while(add != 20 && multi != 100);
{
System.out.println(a);
System.out.println(b);
System.out.println("Total Number of iteration: " +i);
}
}
}
here I'm getting output like
...
19
1
Total Number of iteration: 76
or
...
15
5
Total Number of iteration: 118
Why While loop is ending even only one condition is true and the other is not?
Upvotes: 1
Views: 490
Reputation: 1422
Because your terminating condition is not correct.
Suppose,
a = 17 and b= 3,
Then,
add = 20 and multi = 51,
add != 20 (false) && multi != 100 (true) => false
So, when while gets false, it terminates the loop.
In other cases,
Suppose,
a = 87 and b= 38,
add = 125 and multi = 3306,
add != 20 (true) && multi != 100 (true) => true
So, while does not break.
Your termination logic should be when both false only that time it will return false.
The way you can achieve this is:
add != 20 || multi != 100
Upvotes: 1
Reputation: 26
Maybe, You make mistakes on condition. it will be OR.
do{
a = r.nextInt(99)+1;
b = r.nextInt(99)+1;
add = a+b;
multi = a*b;
i++;
System.out.println("iteration number : " +i);
}
while(add != 20 || multi != 100);
Upvotes: 0