[英]Issue with reading and storing data from .txt file into array
Program: 程序:
The above is what I am trying to achieve; 以上是我要实现的目标; however, the program is not working. 但是,该程序无法正常工作。 *Look below for an example... *下面看一个例子...
class tester
{
public static int x = 0;
public static double[] dataArray = new double[x];//array storing elements
public static void main(String[] args) throws IOException
{
//userInput .txt
Scanner sc = new Scanner(System.in);
System.out.println("Enter filename:\n");
String name = sc.nextLine();
File file = new File(name);
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String newString = stringBuffer.toString();
String [] stringArray = newString.split("\n");
double [] dataArray = new double[stringArray.length];
for(int i=0 ; i < stringArray.length ; i++)
{
dataArray[i] = Double.parseDouble(stringArray[i]);
}
I have a file named: Ben.txt that looks like this: 我有一个名为:Ben.txt的文件,看起来像这样:
1
2
3
4
5
6
7
8
9
10
When I run the program... 当我运行程序时...
Enter filename:
c:/Ben.txt
Exception in thread "main" java.lang.NumberFormatException: empty String
at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
at sun.misc.FloatingDecimal.parseDouble(Unknown Source)
at java.lang.Double.parseDouble(Unknown Source)
at tester.main(tester.java:27)
The problem is you are not actually reading anything from the file. 问题是您实际上没有从文件中读取任何内容。 You do all the setup but you aren't reading. 您已完成所有设置,但没有阅读。
So when you have: 所以当你有:
File file = new File(name);
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String newString = stringBuffer.toString();
Here I don't think you actually need a StringBuffer, all you have to add/replace is this 在这里,我认为您实际上并不需要StringBuffer,只需添加/替换即可。
String str;
str = bufferedReader.readLine();
If you want to read the whole file all you have to do is iterate over the entire file using readLine(). 如果要读取整个文件,则只需使用readLine()遍历整个文件即可。
As GiantTree said, you are not actually reading in the file at all 正如GiantTree所说,您实际上根本没有读取文件
Changing the definition of newString to the following will give you some progress. 将newString的定义更改为以下内容将为您带来一些进步。
String newString = bufferedReader.readLine();
Other things you should consider: 您应该考虑的其他事项:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.