如何获得有效的整数输入但允许用户输入空值?
How to get a valid integer input but allows null input from user?
我想反复要求用户输入一个整数,又让他们取消。我有这个:
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");
}
}
它反复要求有效输入,但当我按下 'cancel' 按钮时,它仍然不断询问。我该如何解决这个问题?
谢谢。
我认为这可行:
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;
}
}
我想反复要求用户输入一个整数,又让他们取消。我有这个:
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");
}
}
它反复要求有效输入,但当我按下 'cancel' 按钮时,它仍然不断询问。我该如何解决这个问题?
谢谢。
我认为这可行:
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;
}
}