如何让JOptionPane接受整数但不接受String?

问题描述 投票:0回答:1

我正在尝试将验证添加到我的代码中(正如我的兄弟所说)并且它应该只接受数字而不是字母,因为它在数组中移动。我尝试了不同的方法,但它仍然接受字母,如果没有,它会在数组[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;
javascript java arrays if-statement joptionpane
1个回答
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;
}
© www.soinside.com 2019 - 2024. All rights reserved.