Reputation: 43
I am trying with a Utility function to get int and check if bad input results in
NumberFormat Exceptions,is there a way to work with Non-decimal Int for below function
//--- Utility function to get int using a dialog.
public static int getInt(String mess) {
int val;
while (true) { // loop until we get a valid int
String s = JOptionPane.showInputDialog(null, mess);
try {
val = Integer.parseInt(s);
break; // exit loop with valid int
} catch (NumberFormatException nx) {
JOptionPane.showMessageDialog(null, "Enter valid integer");
}
}
return val;
}
//end getInt
Upvotes: 0
Views: 163
Reputation: 1257
If I understand you... maybe you can do this:
public static int getInt(String mess) {
int val;
while (true) { // loop until we get a valid int
String s = JOptionPane.showInputDialog(null, mess);
try {
if(mess.match("^\d+$")){ // Check if it's only numbers (no comma, no dot, only numeric characters)
val = Integer.parseInt(s); // Check if it's in the range for Integer numbers.
break; // exit loop with valid int
} else {
JOptionPane.showMessageDialog(null, "Enter valid integer");
}
} catch (NumberFormatException nx) {
JOptionPane.showMessageDialog(null, "Enter valid integer");
}
}
return val;
}
Upvotes: 1
Reputation: 859
Try what u want , one for decimal checker and one for non-decimal int
// for deciaml
public static Boolean numberValidate(String text) {
String expression = "^[+-]?(?:\\d+\\.?\\d*|\\d*\\.?\\d+)[\\r\\n]*$";
CharSequence inputStr = text;
Pattern pattern = Pattern.compile(expression);
Matcher matcher = pattern.matcher(inputStr);
if (matcher.find()) {
MatchResult mResult = matcher.toMatchResult();
String result = mResult.group();
return true;
}
return false;
}
// non-decimal int
public static Boolean numberValidate(String text) {
String expression = "[a-zA-Z]";
CharSequence inputStr = text;
Pattern pattern = Pattern.compile(expression);
Matcher matcher = pattern.matcher(inputStr);
if (matcher.find()) {
MatchResult mResult = matcher.toMatchResult();
String result = mResult.group();
return true;
}
return false;
}
Upvotes: 0