繁体   English   中英

转换由文件产生的ArrayList,该文件的元素分隔为Java中的Integer Array

[英]Convert an ArrayList produced by file whose elements seperated to Integer Array in Java

我对Java中的File操作非常陌生。 我有一个由数字组成的文件,如下所示。

6

1 2

1 3

我试图将所有这些数字在文件中放入整数数组。 我找到了准备好的代码,将它们放在字符串列表中,但现在对我来说并不是没有用的。 我想做的是将它们存储在一个int数组中,并通过索引到达它们。 我想拥有int [] NumbersFromFile = {6,1,2,1,3}; 这是我的代码

 public String[] ReadNumbersFromFile(String name) throws FileNotFoundException {
    String token1 = "";

    Scanner inFile1 = new Scanner(new File(name)).useDelimiter(",\\s*");

    ArrayList<String> temps = new ArrayList<String>();

    // while loop
    while (inFile1.hasNext()) {
       // find next line
       token1 = inFile1.next();
       temps.add(token1);
    }
    inFile1.close();
    String[] tempsArray = new String[temps.size()];
    tempsArray = temps.toArray(tempsArray);

    for (String s  : tempsArray)
    {
       System.out.print(s);
    }

    return tempsArray;
 }            

如何从此文件获取int数组? 提前致谢。

更改此行:

ArrayList<String> temps = new ArrayList<String>();

对此:

ArrayList<Integer> temps = new ArrayList<Integer>();

并更改此行:

token1 = inFile1.next();

对此:

token1 = inFile1.nextInt();

或者,您可以编写一个for循环,以使用Integer.parseInt(yourInt)将ArrayList解析为int []。

int[] ints = new int[temps.size()];
for(int i = 0; i < temsp.size(); i++) {
    ints[i] = Integer.parseInt(temps.get(i));
}

遍历arrayList并添加到int []而不是string [],如下所示:

public int[] ReadNumbersFromFile(String name) throws FileNotFoundException {
    //String to store each number from the file
    String token1 = "";

    //Open the file and create a scanner to read it
    Scanner inFile1 = new Scanner(new File(name));

    //temporary arrayList to store what we read from the file
    //scanners return strings
    ArrayList<String> temps = new ArrayList<String>();

    // while the scanner can see it has more to read
    while (inFile1.hasNext()) {
        // save the number read
        token1 = inFile1.next();

        //add it to the arrayList
        temps.add(token1);
    }

    //close the scanner when done using to free up that resource
    inFile1.close();

    //create the standard int array that is the same length as the arrayList<String>
    int[] tempsArray = new int[temps.size()];

    //loop through the arrayList<String>
    //this is what contains each number from the file, just as Strings
    for(int i = 0; i < temps.size(); i++) {
        //Integar.parseInt(String s) takes a string of numbers and returns it as int
        //save this to our int[]
        tempsArray[i] = Integer.parseInt(temps.get(i));
    }

    //return the int[]
    return tempsArray;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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