0

我正在为我正在创建的应用程序开发我的图形用户界面。基本上有这个 JTextField 用户必须输入整数。例如

25、50、80、90

现在,我有另一个类需要获取这些值并将它们放入一个 int 数组中。

我试过以下。

guiV = dropTheseText.getText().split(",");

在另一个类文件中,我检索了字符串,但我不知道如何获取每个类的值。

最后我只是想得到类似的东西

int[] vD = {textfieldvaluessplitbycommahere};

对 Java 来说还是很新,但这让我抓狂。

4

5 回答 5

0

Try this code:

public int[] getAsIntArray(String str)
{
    String[] values = str.getText().split(",");
    int[] intValues = new int[values.length];
    for(int index = 0; index < values.length; index++)
    {
        intValues[index] = Integer.parseInt(values[index]);
    }
    return intValues;
}
于 2013-06-23T09:30:18.530 回答
0
private JTextField txtValues = new JTextField("25, 50, 80, 90"); 

// Strip the whitespaces using a regex since they will throw errors
// when converting to integers
String values = txtValues.getText().replaceAll("\\s","");

// Get the inserted values of the text field and use the comma as a separator.
// The values will be returned as a string array
private String[] strValues = values.split(",");

// Initialize int array
private int[] intValues = new int[strValues.length()];
// Convert each string value to an integer value and put it into the integer array
for(int i = 0; i < strValues.length(); i++) {
    try {
       intValues[i] = Integer.parseInt(strValues[i]);
    } catch (NumberFormatException nfe) {
       // The string does not contain a parsable integer.
    }

}
于 2013-06-23T00:59:35.303 回答
0

就像你一样fairly new to Java,我不会给你代码片段,而是给你一些指示:

  1. 使用 String 类:它有一个将 String 拆分为 String 数组的方法。
  2. 然后使用 Integer 类:它有一个将 String 转换为 int 的方法。
于 2013-06-23T00:47:38.760 回答
0

你不能直接这样做,你可能需要添加一个方法来将你的字符串数组转换为 int 数组。像这样的东西:

public int[] convertStringToIntArray(String strArray[]) {
    int[] intArray = new int[strArray.length];
    for(int i = 0; i < strArray.length; i++) {
        intArray[i] = Integer.parseInt(strArray[i]);
    }
    return intArray;
}

将您的 guiV 传递给此方法并取回 int 数组

于 2013-06-23T00:48:00.247 回答
0

一个简单的解决方案是一个函数帽子进行转换:

public static int[] convertTextFieldCommaSeparatedIntegerStringToIntArray(String fieldText) {
    String[] tmp = fieldText.split(",");
    int[] result = new int[tmp.length];

    for(int i = 0; i < tmp.length; i++) {
        result[i] = Integer.parseInt(tmp[i].trim());
    }

    return result;
}

基本的方法是:

split用于在逗号处拆分原始输入。

parseInt用于转换 String -> int。Integer的valueOf函数是一个选项,但你必须转换 String -> Integer -> int。


笔记:

您应该使用trim来消除空格。此外,您应该捕获parseInt 抛出的NumberFormatException 。作为未经检查的异常,您不需要捕获它,但检查用户输入并在必要时对其进行清理总是明智的。

于 2013-06-23T00:48:31.190 回答