简体   繁体   中英

Why is my loop skipping this conditional?

Time for my daily newbie Java question :-D

I must not be understanding conditionals in a while loop correctly.

I have this:

while (true){

     if (){
       ...
     } else {
       ...
     }
     if (){
       ...
     } else {
       ...
     }
     if (SENTINEL){
       break;
     }
 }

The first if/else statement is working, and the sentinel is working, but the second if statement gets skipped. If I flip the first and second if statement, then the first if statement still always gets executed and skips the second. What am I missing?

Can I have two if/else statements in one block like this?

I'll include the whole code, though it's pretty ugly, and I'm sure I'll get lots of people telling me better ways of doing this. I don't mind learning better ways, but for now, I just want an answer to this looping question. thanks!

public class FindRange extends ConsoleProgram {

    private static final int SENTINEL = 0;

    int value = 0;
    int highNumber = 0;
    int latestValue = 0;
    int lowNumber = 0;

    public void run() {         
        addNumbers();
    }

    private void addNumbers(){

        value = readInt("Enter number:");

        while(true){
            if (value == SENTINEL){
                break;
            }
            latestValue = readInt("Enter number:");
            getHighNumber();
            getLowNumber();         
            if (latestValue == SENTINEL){
                break;
            }
        }

        println("High Number is "+highNumber+".");
        println("Low Number is "+lowNumber+".");
    }

    private void getHighNumber(){
        if (latestValue >= value){
            highNumber = latestValue;
        }else {
            highNumber = value;
        }

    }
    private void getLowNumber(){
        if (latestValue <= value){
            lowNumber = latestValue;
        }else {
            lowNumber = value;
        }
    }
}

Are you trying to find the minimum and maximum of a series of numbers? If so, you should definitely use Math.min() and Math.max() . It's much clearer that way and you can do away with the if statements. It's also simple enough to do it in the loop with local variables instead of fields.

The common idiom is something like this:

minValue = Math.min(minValue, candidateValue);
maxValue = Math.max(maxValue, candidatevalue);

You can definitely have 2 if/else blocks within the loop; however if your sentinel gets hit the loop will exit.

Posting the entire block would help.


What will happen (after reading the posted code) is when any new value you enter within the loop is greater than the original value, lowNumber is set back to the original. So for example if your input is: 7 6 5 8 Your corresponding low number values will be: 7 6 5 7 Which is incorrect. What you could do is toast the "value" variable altogether, set your low and high to the original value, then compare latest with low and high in the get* methods.

It's possible that the behavior you're seeing comes from the fact that you are always comparing the latest value to the initial value. The initial value will never change-- so if you put in the following input:

20, 60, 50

the high value that gets reported would be 50. That's because 50 is the most recent value to be greater than 20. I think you probably mean to compare the latest value to the high value, no?

Shouldn't you be setting value = latestValue at the bottom of your while loop?

Value never gets updated after the initial read... maybe something like this:

public class FindRange extends ConsoleProgram {

    private static final int SENTINEL = 0;

    public void run() {         
        addNumbers();
    }

    private void addNumbers() {

        int value = 0;
        // Set this to highest possible value
        int highNumber = Integer.MIN_VALUE;
        // Set this to lowest possible value
        int lowNumber = Integer.MAX_VALUE;

        while (true) {

            value = readInt("Enter number:");
            if (value == SENTINEL)
                break;

            lowNumber = Math.min(lowNumber, value);
            highNumber = Math.max(highNumber, value);
        }

        println("High Number is " + Integer.toString(highNumber) + ".");
        println("Low Number is " + Integer.toString(lowNumber) + ".");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM