所以我有一个文本文件,其中的项目如下所示:
350279 1 11:54 107.15
350280 3 11:55 81.27
350281 2 11:57 82.11
350282 0 11:58 92.43
350283 3 11:59 86.11
我正在尝试根据这些值创建数组,其中每行的第一个值位于数组中,每行的第二个值位于数组中,依此类推。
这就是我现在拥有的所有代码,但我似乎不知道如何做到这一点。
package sales;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Sales {
public static void main (String[] args) throws FileNotFoundException {
Scanner reader = new Scanner(new File("sales.txt"));
int[] transID = new int[reader.nextInt()];
int[] transCode = new int[reader.nextInt()];
String[] time = new String[reader.next()];
double[] trasAmount = new double[reader.hasNextDouble()];
}
}
最佳答案
以这种方式构建数组很困难,因为数组具有固定大小......您需要知道它们有多少个元素。如果您使用List
,则不必担心提前知道元素的数量。试试这个(注意:这里没有错误检查!):
public static void main (String[] args) throws FileNotFoundException {
Scanner reader = new Scanner(new File("sales.txt"));
List<Integer> ids = new LinkedList<>();
List<Integer> codes = new LinkedList<>();
List<String> times = new LinkedList<>();
List<Double> amounts = new LinkedList<>();
// Load elements into Lists. Note: you can just use the lists if you want
while(reader.hasNext()) {
ids.add(reader.nextInt());
codes.add(reader.nextInt());
times.add(reader.next());
amounts.add(reader.nextDouble());
}
// Create arrays
int[] idArray = new int[ids.size()];
int[] codesArray = new int[codes.size()];
String[] timesArray = new String[times.size()];
double[] amountsArray = new double[amounts.size()];
// Load elements into arrays
int index = 0;
for(Integer i : ids) {
idArray[index++] = i;
}
index = 0;
for(Integer i : codes) {
codesArray[index++] = i;
}
index = 0;
for(String i : times) {
timesArray[index++] = i;
}
index = 0;
for(Double i : ids) {
amountsArray[index++] = i;
}
}
关于java - 将文件中的数据存储到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16344101/