我已经验证输入的字符串是数字。
while (true) {
try {
numberOfmiles = Double.parseDouble(JOptionPane.showInputDialog(null," Enter Positive Number"));
break;
}
catch (NumberFormatException nfs) {
JOptionPane.showMessageDialog(null, "Please Enter a Positive number");
}
}
我还需要检查它是否为正数。我该怎么做?
答案 0 :(得分:0)
尝试:
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);
答案 1 :(得分:0)
if (numberOfmiles <0)
JOptionPane.showMessageDialog(null, "Warning, enter positive numbers only");
答案 2 :(得分:0)
我假设你有一个用作输入的文本域试试这个:
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
}
:)
答案 3 :(得分:0)
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");
}
}