[英]How can I validate a numeric input in java?
I've validated that the entered string is a number. 我已验证输入的字符串是数字。
while (true) {
try {
numberOfmiles = Double.parseDouble(JOptionPane.showInputDialog(null," Enter Positive Number"));
break;
}
catch (NumberFormatException nfs) {
JOptionPane.showMessageDialog(null, "Please Enter a Positive number");
}
}
I need to also check that it is a positive number. 我还需要检查它是否为正数。 How would I do that? 我该怎么做?
Try: 尝试:
double numberOfMiles;
do{
try{
numberOfmiles = Double.parseDouble(JOptionPane.showInputDialog(null," Enter Positive Number"));
}catch(NumberFormatException nfe){
JOptionPane.showMessageDialog(null, "Please Enter a Positive number");
numberOfMiles = -1;
}
}while(numberOfMiles < 0);
if (numberOfmiles <0)
JOptionPane.showMessageDialog(null, "Warning, enter positive numbers only");
I assume you have a textfield used as input try this: 我假设您有一个文本字段用作输入,请尝试以下操作:
private void jTextField1KeyTyped(java.awt.event.KeyEvent evt) {
char c = evt.getKeyChar();
if ( ((c<'0')||(c>'9'))&& (c != KeyEvent.VK_BACKSPACE))
{
JOptionPane.showMessageDialog(null, "Just positive numbers are allowed");
}
else
{
//non action until a button is pressed
}
:) :)
while(true){
String userInput=JOptionPane.showInputDialog(null," Enter Positive Number");
if(userInput.matches("^\\d+(.\\d+)?$")){
double numberOfmiles=Double.parseDouble(userInput);
if (numberOfmiles <0){
JOptionPane.showMessageDialog(null, "Warning, enter positive numbers only")
}
else{
//successful input
break;
}
}
else{
JOptionPane.showMessageDialog(null, "Just positive numbers are allowed");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.