Reputation: 53
int a=25:
for (double i=1;i<=a;i++)
{
int b=5*i;
boolean value= b==a;
System.out.println(value);
}
This method is true when i=5 but false otherwise. So the value can be true at i=5 but my program will print for me : false-false-false-false-TRUE-false-false-false... how can I make this program to print just TRUE for me. PS: I know that false or false or TRUE or false = True.. but how can I use it in the for loop?
Upvotes: 0
Views: 8832
Reputation: 1
int a = 25;
for (double i = 1; i <= a; i++) {
double b = 5 * i;
if (b == a) {
boolean value = b == a;
System.out.println(value);
}
}
This will work
Upvotes: 0
Reputation: 5094
Like this:
int a=25,b:
boolean value;
for (double i=1;i<=a;i++) {
b=5*i;
value = (b==i);
if (value) {
System.out.println(value);
}
}
also never baeware of declaring variables inside loop body since they are redeclared in each iteration - it is bad pratice.
EDIT: LoL, this code always prints false, it cannot print true since
b=5*i;
and 5*i is never equal to i
EDIT^2:
As CodeGuru suggested, with a==i it prints true only once:
int a=25,b;
boolean value;
for (double i=1;i<=a;i++) {
b=5*(int)i;
value= i==a;
if (value) {
System.out.println(value);
}
}
Upvotes: 1
Reputation: 129507
Maybe this?
int a=25;
for (double i=1;i<=a;i++) {
int b = 5 * (int)i; // you must cast "i" in order for this to compile
boolean value = b == a; // you probably wanted "b == a" not "b == i"
if (value)
System.out.println("true");
}
i.e. we print "true"
only if value
is true
.
To stop the loop when value
becomes true
, we can use a break
statement:
int a=25;
for (double i=1;i<=a;i++) {
int b = 5 * (int)i;
boolean value = b == a;
if (value) {
System.out.println("true");
break;
}
}
Upvotes: 4
Reputation: 83527
One way to do this is similar to adding a list of numbers. You need an accumulator which is a variable that holds the result so far. Declare this before the loop:
boolean value = false;
Now inside the loop, use the |=
operator:
value |= (b == i);
However, this seems like an ugly solution. What are you going to do with the true
value when you find it?
Upvotes: 0