我正在尝试向我的代码添加验证(如我的兄弟所说),并且它在数组中移动时仅应接受数字,而不接受字母。我尝试了不同的方法,但是它仍然接受字母,如果没有,它会在array [1]时崩溃。 这是我的代码的一部分:
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;
答案 0 :(得分:0)
我了解您想要做什么,但是我不确定自己代码的最终目的是什么。我问的原因是,带有数字列表的ComboBox可能更适合您的InputBox对话框。
如您所知,“输入框”对话框将返回一个字符串。您需要确保输入的实际上是一个数值。为此,您可以将String#matches()方法与Regular Expression一起使用,例如:
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;
}