繁体   English   中英

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

[英]How to let JOptionPane accept integer but not String?

我正在尝试将验证添加到我的代码中(正如我的兄弟所说)并且它应该只接受数字而不是字母,因为它在数组中移动。 我尝试了不同的方法,但它仍然接受字母,如果没有,它会在数组[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;

我理解你想做什么,但我不确定你的代码的最终目的是什么。 我问的原因是,带有数字列表的ComboBox可能更适合您的InputBox对话框。

如您所知,输入框对话框将返回一个字符串。 您需要确保输入的内容实际上是一个数值。 为此,您可以使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM