如何从字符串数组中获取int数组

时间:2015-01-30 09:22:16

标签: java android arrays

File myFile = new File(
    Environment.getExternalStorageDirectory().getAbsolutePath(),
    "Notes/test.txt"
);
BufferedReader br = new BufferedReader(new FileReader(myFile));
String line = br.readLine();
while ((line = br.readLine()) != null) {
    b = line.split(",");
    xpoints = new int[b[0].length()];
    ypoints = new int[b[1].length()];
    for (int i = 1; i < b[0].length(); i++) {
        xpoints[i] = Integer.parseInt(b[0]);
        ypoints[i] = Integer.parseInt(b[1]);                
    }
    /*direction(xpoints, ypoints);*/
}
br.close();

这里,我从b [0]和b [1]得到X和Y值。我想将这些值存储在整数数组中(如int [] x和int [] y)。我可以如前所述在数组中获取所有这些值吗?

7 个答案:

答案 0 :(得分:4)

您应该将String解析为int,如:

x[i] = Integer.parseInt(str);

表示每个String元素的每个int表示

注意提供str虽然只有整数,因为否则会抛出NumberFormatException

答案 1 :(得分:0)

您可以在循环中迭代String数组,然后将值存储在相同大小的int数组中。

int[] intArray = new int[b.length];
for(int i = 0; i < b.length; i++){
    try{
        intArray[i] = Integer.parseInt(b[i]);
    catch(NumberFormatException e){
        //handle exception
    }
}

答案 2 :(得分:0)

您可以使用Integer.parseInt()方法将字符串转换为整数。你必须通过每个字符串数组元素来使用上面的方法。以下代码可以根据您的要求在任何地方使用。

    int[] x = new int[2];
    x[0] = Integer.parseInt(b[0]);
    x[1] = Integer.parseInt(b[1]);

答案 3 :(得分:0)

在你的while语句中进行拆分时,请执行以下操作:

String[] b = line.split(splitsby);
int[] intArray = new int[b.length];
for (int stringIndex = 0; stringIndex < b.length; stringIndex++) {
    intArray[stringIndex] = Integer.parseInt(b[stringIndex]);
}
System.out.println("X = " + intArray[0] + " Y = " + intArray[1]);

这假设b中的每个值都可以解析为Integer

答案 4 :(得分:0)

由于您不知道从文件中获取的元素的确切大小,我建议您创建一个ArrayList。

Arralist<Integer> a=new ArrayList<Integer>();
Arralist<Integer> b=new ArrayList<Integer>();

然后

File myFile = new File(Environment
                        .getExternalStorageDirectory().getAbsolutePath(),
                        "Notes/test.txt");
BufferedReader br = new BufferedReader(new FileReader(myFile));
String line=br.readLine();
String splitsby = ",";
while ((line = br.readLine()) !=null) {
     String[] b=line.split(splitsby);
     System.out.println("X = "+b[0]+" Y = "+b[1]);
     a.add(Integer.parseInt(b[0]);
     b.add(Integer.parseInt(b[1]);
}
br.close();

答案 5 :(得分:0)

您可以添加此方法:

private ArrayList<Integer> getIntegerArray(ArrayList<String> stringArray) {
    ArrayList<Integer> result = new ArrayList<Integer>();
    for(String stringValue : stringArray) {
        try {
            // convert String to Integer and store it into integer array list
            result.add(Integer.parseInt(stringValue));
        } catch (NumberFormatException nfe) {
            // System.out.println("Could not parse " + nfe);
            Log.w("NumberFormat", "Parsing failed! " + stringValue + " can not be an integer");
        } 
    }       
    return result;
}

答案 6 :(得分:-1)

的Integer.parseInt(B [0]); 有关更多信息,请参阅Javadoc。

相关问题