[英]How to let JOptionPane accept integer but not String?
I am trying to add validation to my code (as my brother puts it) and that it should only accept numbers and not letters as it moves through the array. 我正在尝试将验证添加到我的代码中(正如我的兄弟所说)并且它应该只接受数字而不是字母,因为它在数组中移动。 I have tried different methods but it still accepts letters and if it doesn't it crashes at array[1].
我尝试了不同的方法,但它仍然接受字母,如果没有,它会在数组[1]崩溃。 here's the part of my code:
这是我的代码的一部分:
public static void main(String[]Terminal) {
String Choice;
char response1;
String response = null;
String Display = null;
String TryAgain = null;
String Element = null;
boolean Validation = true;
int numberOfElements = 5; //array element numbers
int index;
int Choice1;
int[] Array = new int[numberOfElements]; //array
do { // Rewind Option
do {
for (index = 0; index < numberOfElements; index++) { // Loop for Array Input
if(index==0) //Dialog Design, tied to Loop
{Element = "First";}
else if
(index==1) {Element = "Second";}
else if
(index==2) {Element = "Third";}
else if
(index==3) {Element = "Fourth";}
else if
(index==4) {Element = "Fifth";}
response = JOptionPane.showInputDialog(null, "Enter the " + Element + " (" +(index+1)+ "): " ); //Display Dialog
// the validation should be here right?
}
int Array1 = Integer.parseInt(response);
Array[index] = Array1;
I understand what you want to do but I'm not really sure what the ultimate purpose of your code is for. 我理解你想做什么,但我不确定你的代码的最终目的是什么。 The reason I ask is that there may be a possibility that a ComboBox with a numerical list may be better suited for your InputBox dialog.
我问的原因是,带有数字列表的ComboBox可能更适合您的InputBox对话框。
As you know your Input Box dialog will return a string. 如您所知,输入框对话框将返回一个字符串。 You need to ensure that what was entered was in fact a numerical value.
您需要确保输入的内容实际上是一个数值。 To do this you can use the String#matches() method along with a Regular Expression , for example:
为此,您可以使用String#matches()方法和正则表达式 ,例如:
while(true) {
//Display Dialog
response = JOptionPane.showInputDialog(null, "Enter the " + Element +
" (" +(index+1)+ "): " );
if (!response.matches("\\d+") {
JOptionPane.showMessageDialog(null, "The data you entered is not a
valid Numerical Value (" + response + ").",
"Invalid Input", JOptionPane.WARNING_MESSAGE);
continue;
}
break;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.