[英]How to store data from text file to an object array?
I already read data from a text file (in the file there are all numbers (int and double)) and in my class, I have an array of an object type. 我已经从文本文件读取了数据(文件中有所有数字(int和double)),在我的课堂上,我有一个对象类型的数组。 I have no idea how to put data which read from the txt file into the array. 我不知道如何将从txt文件读取的数据放入数组。
I would greatly appreciate it if you can give me some answers. 如果您能给我一些答案,我将不胜感激。
this.object=new Object[nums1];
File file=new File("/homes/xx.txt");
try {
Scanner scnr=new Scanner(file);
int lineNumber= 1;
while (scnr.hasNextLine()) {
String line = scnr.nextLine();
System.out.println(line);
}
}
catch (FileNotFoundException e) {
System.out.println(e);
}
A couple of sample lines from my input file: 输入文件中的一些示例行:
3
1.0 2.5 3.0
I think I need to distinguish between whole numbers and numbers with a decimal point. 我想我需要区分整数和带小数点的数字。 Should I create another object type so I can store int
and double
separately? 是否应该创建其他对象类型,以便分别存储int
和double
?
try this: 尝试这个:
File file=new File("/homes/xx.txt");
try {
Scanner scnr=new Scanner(file);
List<String> lines = new ArrayList<String>();
while (scnr.hasNextLine()) {
lines.add(scnr.nextLine());
System.out.println(lines);
}
String[] arr = lines.toArray(new String[0]);
}
catch (FileNotFoundException e) {
System.out.println(e);
If you have a space between your integers and doubles, try this: 如果整数和双精度之间有空格,请尝试以下操作:
Object []objects = file;
Object []numbers = objects.split(“ “);
I am not sure about Object []objects = file;
我不确定Object []objects = file;
part because I am new java learner too. 部分原因是我也是Java新手。 But if you can insert whole text to an array, you can split and assign values one by one with .split
command to another array. 但是,如果您可以将整个文本插入到数组中,则可以使用.split
命令将值一一拆分并分配给另一个数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.