Java:将文件中的整数读入数组 [英] Java: Reading integers from a file into an array
本文介绍了Java:将文件中的整数读入数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
File fil = new File("Tall.txt");
FileReader inputFil = new FileReader(fil);
BufferedReader in = new BufferedReader(inputFil);
int [] tall = new int [100];
String s =in.readLine();
while(s!=null)
{
int i = 0;
tall[i] = Integer.parseInt(s); //this is line 19
System.out.println(tall[i]);
s = in.readLine();
}
in.close();
我正在尝试使用文件Tall.txt"将其中包含的整数写入名为tall"的数组中.它在某种程度上做到了这一点,但当我运行它时,它也会抛出以下异常 (:
I am trying to use the file "Tall.txt" to write the integers contained in them into the array named "tall". It does this to some extent, but also when I run it, it throws the following exception (:
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at BinarySok.main(BinarySok.java:19)
它究竟为什么会这样做,我该如何删除它?在我看来,我将文件作为字符串读取,然后将其转换为整数,这并不违法.
Why exactly does it do this, and how do I remove it? As I see it, I read the file as strings, and then convert it to ints, which isn't illegal.
推荐答案
你可能想做这样的事情(如果你在 Java 5 & up)
You might want to do something like this (if you're in java 5 & up)
Scanner scanner = new Scanner(new File("tall.txt"));
int [] tall = new int [100];
int i = 0;
while(scanner.hasNextInt()){
tall[i++] = scanner.nextInt();
}
这篇关于Java:将文件中的整数读入数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文