Я хотел бы выполнить проверку, которая будет принимать из текстового поля число (String), а затем передать его двойной переменной, если ее Int или double, иначе будет создано новое исключение.Подтвердить только на Java Только int и double numbers
Я уже реализовал код, который работает только для номеров Int. не могли бы вы дать мне подсказку, пожалуйста?
protected double validateDiameter() {
try {
if (stringDiameter != null) {
//Checking stringDiameter if its a number by creating a for loop
//that check each character of the string.
//If the string contains only numbers
//the program will continue, if not an exception is thrown.
int lengthofdiameter = stringDiameter.length();
int DiameterCount = 0;
for (int i = 0; i <= lengthofdiameter - 1; i++) {
char t = stringDiameter.charAt(i);
if (Character.isDigit(t)) {
DiameterCount++;
}
}
if (lengthofdiameter == DiameterCount) {
Diameter = Double.parseDouble(stringDiameter);
if (Diameter <= 0 && Diameter >= 9) {
throw new Exception("");
}
} else {
throw new Exception("");
}
}
} catch (Exception e) {
Diameter = 0.0;
JOptionPane.showMessageDialog(null,
"Wrong value on the input area.Please use number." + "\n" + "Check diameter input.",
"Error message!",
JOptionPane.ERROR_MESSAGE);
}
return Diameter;
}
Спасибо
Обновлено:
Спасибо всем за вашу помощь. Я очень ценю это. Решение, которое работало для меня:
protected double validateDiameter() {
try {
if (stringDiameter != null) {
if (stringDiameter.matches("-?\\d+(\\.\\d+)?")) {
Diameter = Double.parseDouble(stringDiameter);
} else {
throw new Exception("");
}
if (Diameter <= 0 || Diameter > 8) {
throw new Exception("");
}
} else {
throw new Exception("");
}
} catch (Exception e) {
Diameter = 0.0;
JOptionPane.showMessageDialog(null,
"Wrong value on the input area.Please use number." + "\n" +
"Check diameter input.",
"Error message!",
JOptionPane.ERROR_MESSAGE);
}
return Diameter;
}
Оба ваших ответа выглядят прекрасно, и я могу сказать, что они менее сложные, чем мои. Единственная проблема: Новое исчисление выдается, если вход «Джош», «10.Josh» и т. Д., Но входы, такие как «2.F» или «1.30F», приемлемы, и мне это не нужно. Как я могу делать исключения на этих входах? Спасибо за ваше время. Я очень ценю вашу помощь! – user3047017
@ user3047017 посмотреть мой ответ http://stackoverflow.com/a/20306147/1282908 – nexus
Эй, спасибо за ваш ответ, но обработка исключений необходима. – user3047017