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);
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);
int i = 0;
while(!file.isFile() && i < 3) {
userInput = JOptionPane.showInputDialog("UserInput);
i++;
}
And I agree that for loop is better choice :)
Use a for loop instead :
for (int i = 0; i < 3 && !file.isFile(); i++) {
userInput = JOptionPane.showInputDialog("UserInput");
...
}
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.
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.
int i = 3;
while(!file.isFile() && i>0) {
userInput = JOptionPane.showInputDialog("UserInput");
i--;
}
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.