我正在尝试创建一个void方法,它将读取csv文件并计算reputaion状态数,例如TX的次数,多少次哦和Dc的次数。输出应该是-TX = 4; OH = 2; DC = 2。但我的输出是“输入字符串:”F“” - 我真的无法得到问题在哪里。有人帮我吗?
“Crimerate.csv”
州县税率
TX,达拉斯,39
TX,Aderson,10喔,射手,20
DC,DC,50
TX,休斯敦,31
TX,Claude,13喔,贝克萨尔,10 DC,SE,40
public static void countnumber()
{
try{
List<String>number=Files.readAllLines(Paths.get("Crimerate.csv"));
double sum=0,num=0;
for (String line:number){
if(num==0){
++num;
continue;
}
line=line.replace("\"","");
String []result=line.split(",");
double close = Double.parseDouble(result[6]);
String numberAsString = Double.toString(close);
if(numberAsString.equals("Tx"))
{
sum++;
System.out.println("number of Tx =" + sum);
}
else if(numberAsString.equals("Oh"))
{
sum++;
System.out.println("number of Oh =" + sum);
}
else if(numberAsString.equals("Dc"))
{
sum++;
System.out.println("number of Dc =" + sum);
}
}
}catch(Exception e){
System.out.println(e.getMessage());
}
}
public static void main (String args[])
{
countnumber();
}
答案 0 :(得分:1)
虽然之前建议的答案将解决为什么只有一个响应(只有一个和变量的结果)的具体问题,但它们有两个问题。
此解决方案可处理这两种情况。
public static void main(String[] args)
{
Map<String, Integer> countByState = new HashMap<>();
List<String> number;
try {
number = Files.readAllLines(Paths.get("f:/tmp/Crimerate.csv"));
int cntr = 0;
for (String line : number) {
// skip first line
if (cntr++ == 0) {
continue;
}
String []result=line.split(",");
// should add error checking
String state = result[0].toUpperCase();
Integer cnt = countByState.get(state);
if (cnt == null) {
cnt = new Integer(0);
}
countByState.put(state, ++cnt);
}
System.out.println(countByState);
}
catch (IOException e) {
e.printStackTrace();
}
}
示例结果基于问题中显示的数据(该数据中只有一个DC):
{TX = 4,OH = 2,DC = 1}
答案 1 :(得分:0)
int txCount = 0;
int ohCount = 0;
int dcCount = 0; //create this variables inside the class(instance variables)
if(numberAsString.equals("Tx"))
{
++txCount;
System.out.println("number of Tx =" + txCount);
}
else if(numberAsString.equals("Oh"))
{
++ohCount;
System.out.println("number of Oh =" + ohCount);
}
else if(numberAsString.equals("Dc"))
{
++dcCount;
System.out.println("number of Dc =" + dcCount);
} //its better if u use equalsIgnoreCase on if Statements
你在每个if循环上引用相同的sum变量,我已经修复了它。 我假设您在阅读文件时编写的代码是正确的。
答案 2 :(得分:0)
每个总和只需要不同的sum
个变量。并在循环后打印结果。
try{
List<String>number=Files.readAllLines(Paths.get("Crimerate.csv"));
double sumTx=0,sumOh=0,sumDc=0,num=0;
for (String line:number){
if(num==0){
++num;
continue;
}
line=line.replace("\"","");
String []result=line.split(",");
double close = Double.parseDouble(result[6]);
String numberAsString = Double.toString(close);
if(numberAsString.equals("Tx")) {
sumTx++;
} else if(numberAsString.equals("Oh")){
sumOh++;
} else if(numberAsString.equals("Dc")){
sumDc++;
}
}
System.out.println("number of Tx =" + sumTx);
System.out.println("number of Oh =" + sumOh);
System.out.println("number of Dc =" + sumDc);
}catch(Exception e){
System.out.println(e.getMessage());
}
}