我正在尝试让此程序在跳过字符串的第一行之后读取.csv文件并输出数据。
我尝试移动大括号或创建新的try-catch块。我试过将变量移到尝试之外。
import java.io.*;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class USCrimesFile{
public static USCrimes[] read(String filename){
//Declare Array
USCrimes[] stats = new USCrimes[20];
//Declare variables
int count = 0;
String inFile = "Crime.csv";
String line;
@SuppressWarnings({"rawtypes","unchecked"})
try
{
ArrayList storeList = new ArrayList<USCrimes>();
FileInputStream fstream = new FileInputStream(inFile);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read file line by line
strLine = br.readLine();
while ((strLine = br.readLine()) !=null){
storeList.add(read(strLine));
}
in.close();
}
catch (IOException e){
}
try{
Scanner inputReader;
inputReader = new Scanner(new File(filename));
while(inputReader.hasNext()){
line = inputReader.nextLine();
String[] data = line.split(",");
stats[count] = new USCrimes(Integer.parseInt(data[0]));
stats[count].setPopulation(Double.parseDouble(data[1]));
stats[count].setMurderRate(Double.parseDouble(data[5]));
stats[count].setRobberyRate(Double.parseDouble(data[9]));
count++;
}
inputReader.close();
}
catch (IOException e){
System.out.println("File not found.");
}
return stats;
}}
期望它编译但输出错误:类型非法开始 尝试
答案 0 :(得分:2)
问题出在抑制警告注释上
@SuppressWarnings({"rawtypes","unchecked"})
这应该在方法级别或附加到变量storeList
。
其他问题:
catch (IOException e){
}
永远不要默默地吞下异常。如果这里出了问题,您将永远不会知道。
stats[count] = new USCrimes(Integer.parseInt(data[0]));
检查并确保不超过数组大小-尝试使用ArrayList