-4

I want to restrict the while Loop.

I don't want to use break;, instead I want to say that the loop must end after three times.

My while Loop:

while(!file.isFile()) { userInput = JOptionPane.showInputDialog("UserInput);
P45 Imminent
  • 8,319
  • 4
  • 35
  • 78

7 Answers7

4
int i = 0;
while(!file.isFile() && i < 3) {
  userInput = JOptionPane.showInputDialog("UserInput);
  i++;
}

And I agree that for loop is better choice :)

vbuhlev
  • 509
  • 2
  • 10
3

Use a for loop instead :

for (int i = 0; i < 3 && !file.isFile(); i++) {
    userInput = JOptionPane.showInputDialog("UserInput");
    ...
}
Eran
  • 387,369
  • 54
  • 702
  • 768
  • haha i think you win for doing the logical thing and doing for and not just answering with while :P – natus Aug 15 '16 at 12:23
  • 3
    @natus I think that could be debated. Yes, using a for loop for counting is a more common practice; but putting "while" like conditions into a for loop on the other hand ... is not. I think many programmers that encounter a for loop like this might overlook the second condition. Thus, in my eyes, higher potential for running into bugs. Simply because people have different expectations when they see a while loop. – GhostCat Aug 15 '16 at 12:26
  • @GhostCat fair call :) – natus Aug 15 '16 at 12:27
3

Then you need to make your while loop a for-loop like thing:

int counter = 0;

while (counter < 3 && !file.isFile()) { ...
  counter++;

For the record: the code you are showing isn't really useful: you are "overriding" the input you get from the user; and: you are condition !file.isFile() ... will not change its value ... because there is no code that would do that. In other words: there is more to fix about your code than just the way you are looping. It simply seems weird to ask the user the same thing three times; to ignore what he says the first two times.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
3

Consider refactoring to a for loop, introducing a counter variable in a tight scope:

for (int i = 0; i < 3 && !file.isFile(), ++i){
    userInput = JOptionPane.showInputDialog("UserInput"/*ToDo - quotation inserted*/);
}

The for loop conditional check i < 3 && !file.isFile() is verified before the statement in the loop body is ran.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
0
int i = 3;

while(!file.isFile() && i>0) { 
   userInput = JOptionPane.showInputDialog("UserInput");
   i--;
}
ma3stro
  • 313
  • 2
  • 11
0
int count = 0;
while(!file.isFile() && count < 3 ) { 
   count++;
}
brso05
  • 13,142
  • 2
  • 21
  • 40
natus
  • 74
  • 2
  • 8
0
int counter = 0;
while(!file.isFile() && counter < 3) { 
   userInput = JOptionPane.showInputDialog("UserInput);
   counter++;
}

Replace 3 with the number of iterations you would like the loop to be limited to.