2

At university we learned 2 ways to read integers from console, while specific integer is not given. First one is the "Loop and half":

int val = readInt(“Enter val:”);
while (val != SENTINEL) 
    val = readInt(“Enter val:”);
}

They say that it is a bad way because of code duplication val = readInt(“Enter val:”); and they suggest second way to do it "The Repeat-Until-Sentinel Idiom" :

  while (true) {
       value = readInt(“Enter val:”);
       if (value == sentinel) break;
    }

I had teacher,who was more in computer science and he always sad that its better to avoid while(true) and break in programs and don't use them unless emergency, so i am little confused now. Which way is considered as a better solution ?

2 Answers2

1

How about a third solution?

boolean keepReading = true;
while (keepReading) {
    int val = readInt("Enter val");
    if (val == SENTINEL) {
        keepReading = false;
    } 
    else {
        // process the value
    }
}

It's similar to the second one, but doesn't use while(true) and break. I really don't like the first one, because to make it complete, you also have to repeat the check against the sentinel:

int val = readInt(“Enter val:”);
while (val != SENTINEL) 
    val = readInt(“Enter val:”); // duplication
    if (val != SENTINEL) { // duplication
        // process the value 
    }
}
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
1

Yes, the problem with what you refer to as "Loop and half" is that there is a little code duplication. The reason why the one you call "Repeat-Until-Sentinel" is not ideal is that the idiom while(true) is not very expressive of your intent. See Are “while(true)” loops so bad? for another explanation.

In your example, you could do

int value;
while ((value = readInt()) != SENTINEL) {
    System.out.println(value);
}

In java, when you have an assignment operation, the result is returned, so you can compare it without duplicating your code.

The important aspect is that it's more expressive of the intent: You can kind of read it as while the value read is not the sentinel.

Community
  • 1
  • 1
Ed I
  • 7,008
  • 3
  • 41
  • 50