3
string s = Console.ReadLine();
while(s != null)
{
    // do something 
    //   ....
    s = Console.ReadLine(); 
}

The code above is to get the input, verify it, process it and then input again, but obviously, s = Console.ReadLine(); is code duplication.

What tricks are there to avoid the duplication?

2
  • that is the typical pattern of while statement unless you do a while(true) Commented Apr 21, 2014 at 13:18
  • 1
    Which language is this? Most support a do-while loop that is useful for situations like this. Commented Apr 21, 2014 at 13:18

2 Answers 2

2

depending on language, you can often do something like this:

while (s = Console.ReadLine())
{
    ...
}
Sign up to request clarification or add additional context in comments.

2 Comments

Console.ReadLine() doesn't return a bool
This is pretty clearly described as a language agnostic answer. If Java is indeed the target language, then this is pretty easily modified by using while (null != (s = Console.ReadLine()).
2

In Python (where there is no do-while loop to guaranteed at least one iteration), the trick is to use an infinite loop with an explicit break.

while( true )  // Or whatever evaluates to true unconditionally
{
    s = Console.ReadLine();
    if (s == null) {
        break;
    }
    // do something
}

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.