1

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++;
    }
1
  • Excuse me, but why in God's name would you 1) want to use while instead of for, and 2) avoid break? Usually those two intentions make your code a lot harder to read... Commented Dec 9, 2015 at 3:23

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Change

if (x < 0) 
{
    count--;
}
array[index] = x;
index++;

to something like

if (x < 0) 
{
    count--;
} 
else 
{
    array[index] = x;
    index++;
}

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.