javascript如何让JOptionPane接受整数而不是字符串?
我正在尝试向我的代码添加验证(正如我哥哥所说的),它在数组中移动时只接受数字而不接受字母。我尝试了不同的方法,但它仍然接受字母,如果不接受,它将在数组中崩溃[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;
# 1 楼答案
我理解你想做什么,但我不确定你的代码的最终目的是什么。我问这个问题的原因是,有可能带有数字列表的组合框更适合您的InputBox对话框
正如您所知,您的输入框对话框将返回一个字符串。您需要确保输入的实际上是一个数值。为此,可以使用String#matches()方法和Regular Expression方法,例如: