Reputation: 53
I need to convert this for loop into a while loop so I can avoid using a break.
double[] array = new double[100];
Scanner scan = new Scanner(System.in);
for (int index = 0; index < array.length; index++)
{
System.out.print("Sample " + (index+1) + ": ");
double x = scan.nextDouble();
count++;
if (x < 0)
{
count--;
break;
}
array[index] = x;
}
This is what I came up with but I'm getting a different output:
int index = 0;
double x = 0;
while (index < array.length && x >= 0)
{
System.out.print("Sample " + (index+1) + ": ");
x = scan.nextDouble();
count++;
if (x < 0)
{
count--;
}
array[index] = x;
index++;
}
Upvotes: 1
Views: 906
Reputation: 90
this solution gives the same output as the for loop:
while (index < array.length && x >= 0)
{
System.out.print("Sample " + (index+1) + ": ");
x = scan.nextDouble();
count++;
if (x < 0)
{
count--;
}
else
{
array[index] = x;
index++;
}
}
EXPLANATION:
On the for loop you use the break statement so nothing happens after the program hits the break. So array[index] = x;
didn't get executed.
On the while loop since there's no break, the loop continues, so the statements array[index] = x;
and index++;
got executed.
That's why you got different results. If you don't want the statements
array[index] = x;
index++;
To be executed you can simply make your if statement a if/else statement as above.
Upvotes: 1
Reputation: 1864
If you want to avoid break, changing the for loop into a while loop doesn't help in any way.
How about this solution:
boolean exitLoop = false;
for (int index = 0; index < array.length && !exitLoop; index++)
{
System.out.print("Sample " + (index+1) + ": ");
double x = scan.nextDouble();
count++;
if (x < 0)
{
count--;
exitLoop = true;
}
else {
array[index] = x;
}
}
Upvotes: 1
Reputation: 201447
Change
if (x < 0)
{
count--;
}
array[index] = x;
index++;
to something like
if (x < 0)
{
count--;
}
else
{
array[index] = x;
index++;
}
Upvotes: 1