如何验证 java 中的数字输入?
How can I validate a numeric input in java?
我已经验证输入的字符串是一个数字。
while (true) {
try {
numberOfmiles = Double.parseDouble(JOptionPane.showInputDialog(null," Enter Positive Number"));
break;
}
catch (NumberFormatException nfs) {
JOptionPane.showMessageDialog(null, "Please Enter a Positive number");
}
}
我还需要检查它是否为正数。我该怎么做?
尝试:
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");
我假设您有一个用作输入的文本字段试试这个:
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");
}
}
我已经验证输入的字符串是一个数字。
while (true) {
try {
numberOfmiles = Double.parseDouble(JOptionPane.showInputDialog(null," Enter Positive Number"));
break;
}
catch (NumberFormatException nfs) {
JOptionPane.showMessageDialog(null, "Please Enter a Positive number");
}
}
我还需要检查它是否为正数。我该怎么做?
尝试:
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");
我假设您有一个用作输入的文本字段试试这个:
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");
}
}