【发布时间】:2021-03-09 09:07:21
【问题描述】:
试图读取txt文件并将每个类别(品牌、颜色、年份)存储到不同的ArrayLists中,然后显示数组列表中的所有数据。
我得到了什么
*****Welcome *****
setup
所以通过 System.out.println(make.get(i)) 等,我得到了
toyota
subaru
honda
blue
black
white
2010
2001
2003
文本文件如下所示
3
#car
#make
Toyota
#Color
Blue
#year
2010
##
#car
#make
subaru
#color
black
#year
2003
##
#car
#make
honda
#Color
white
#year
2001
##
前面的 3 表示车库里有多少辆车 其中“##”代表汽车详情结束
代码
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
public class testApp {
static ArrayList<String> year= new ArrayList<>();
static ArrayList<String> make = new ArrayList<>();
static ArrayList<String> colors = new ArrayList<>();
private static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("*****Welcome*****");
try {
garage();
} catch (Exception e) {
//System.out.println(e.getMessage());
}
}
public static void garage() throws NumberFormatException, IOException {
System.out.println("setup");
String filename = "garage.txt";
String showError = "Error input file " + filename + " is not formmated properly.";
BufferedReader reader = new BufferedReader(new FileReader(new File(filename)));
String line = reader.readLine();
if (line == null) {
reader.close();
throw new IOException(showError);
}
int numCar= Integer.parseInt(line);
System.out.println("num ques " + numCar);
int carCount = 0;
//loop to look for each car
while ((line = reader.readLine()) != null && carCount < numCar) {
// System.out.println("reading");
if (line.equals("#car")) {
// System.out.println("q");
while ((line = reader.readLine().trim()) != null) {
if (!line.equals("##")) {
//reads car
if (line.equals("#make")) {
make.add(reader.readLine());
System.out.println("q 1 "+make.get(0));
}
if (line.equals("#color")) {
System.out.println("make orig= " + reader.readLine());
colors.add(reader.readLine());
}
if (line.equals("#year")) {
year.add(reader.readLine());
System.out.println("ans orig= " + reader.readLine());
//color = readAnswer(reader.readLine(),car);
}
} else {
break;
}
}
carCount++;
}
}
for (int i = 0; i < 3; i++) {
System.out.println(make.get(i));
System.out.println(year.get(i));
System.out.println(colors.get(i));
}
}
}
【问题讨论】: