我想反复要求用户输入一个整数,但也允许他们取消。我有这个:
int numSelectedCols = 0;
boolean validInput = false;
while(!(numSelectedCols > 0) && !validInput) {
try {
numSelectedCols = Integer.parseInt(JOptionPane.showInputDialog("Enter number of columns to be selected: "));
validInput = true;
}
catch (NumberFormatException e) {
System.out.println("Please enter an integer value");
}
}
它反复询问有效输入但是当我按下“取消”按钮时,它仍然一直在询问。我该如何解决这个问题?
感谢。
答案 0 :(得分:0)
我认为这有效:
while(!validInput) {
input = JOptionPane.showInputDialog("Enter number of columns to be selected: ");
if(input != null) {
try {
numSelectedCols = Integer.parseInt(input);
if(numSelectedCols > 0) {
validInput = true;
}
}
catch (NumberFormatException e) {
System.out.println("Please enter an integer value");
}
}
else {
validInput = true;
}
}