Java的:从文件整数读阵列 [英] Java: Read array of integers from file
问题描述
说我有一个名为input.txt的
一个其中有一帮正整数:
Say i have a file called "input.txt"
that has a bunch of positive integers in it:
6
5
6
8
6
2
4
等等....(每行一个整数)
and so on....(one integer per line)
我要读取该文件,并使其成为一个数组。的第一个整数(在这种情况下,6)告诉阵列中的索引或元件的数量,所以6斑点。其他数字填充阵列中的从0开始。因此,在索引0,数为5,在索引1的数目为6,依此类推。
I want to read this file and make it into an array. The first integer (in this case 6) tells the number of indexes or elements in the array, so 6 spots. The other numbers fill in the array starting at 0. So at index 0, the number is 5, at index 1 the number is 6, and so on.
可有人请告诉我如何读取该文件,并使其成为一个数组称为A和每个索引为n返回整数?
Can someone please show me how to read this file and make it into an array called A and return the integers in each index as n?
这是我迄今为止:
import java.io.*;
public class inputFile {
public static jobScheduleRecursive(int[] A, int i)
{
try
{
FileReader filereader = new FileReader("input.txt");
BufferedReader bufferedreader = new BufferedReader(filereader);
String line = bufferedreader.readLine();
//While we have read in a valid line
while (line != null) {
//Try to parse integer from the String line
try {
System.out.println(Integer.parseInt(line));
} catch (NumberFormatException nfe) {
System.err.println("Failed to parse integer from line:" + line);
System.err.println(nfe.getMessage());
System.exit(1);
}
line = bufferedreader.readLine();
}
}
catch(FileNotFoundException filenotfoundexception)
{
System.out.println("File not found.");
}
catch(IOException ioexception)
{
System.out.println("File input error occured!");
ioexception.printStackTrace();
}
return A;
}
我觉得我做的事情完全错误的。请帮助。
I think i'm doing something completely wrong. please help.
推荐答案
使用的 扫描
和<一个href=\"http://download.oracle.com/javase/6/docs/api/java/util/Scanner.html#nextInt%28%29\"><$c$c>Scanner.nextInt()$c$c>方法,你可以在短短的几行解决这个问题:
Using a Scanner
and the Scanner.nextInt()
method, you can solve this in just a few lines:
Scanner s = new Scanner(new File("input.txt"));
int[] array = new int[s.nextInt()];
for (int i = 0; i < array.length; i++)
array[i] = s.nextInt();
这篇关于Java的:从文件整数读阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!