バッファリーダーがコードの最初の行をスキップしない
温馨提示:
本文最后更新于 2024年04月12日,已超过 48 天没有更新。若文章内的图片失效(无法正常加载),请留言反馈或直接联系我。
バッファリーダーを使用してcsvファイルを読み取っているJavaファイルがあります(コンソールとスキャナも使用してみました)。問題は、コードがCSVの2番目の部分(カンマ後)を意図的に整数しましたとりあえず、多くのことを試してみましたが、csv ファイルの最初の実行をスキップするコードを取得することはできません。常に文字列「COUNT」を整数に変換しようとします。もしこれが今後続くのか知っている人はいますか?
CSV ファイルの最初の行は「NAME, COUNT」ですが、これをスキップしようとしていることに注意してください。
これはコードです:
package util;
//import bakery.*;
import bakery.Ingredient;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.nio.Buffer;
import java.util.ArrayList;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.Console;
public class CardUtils {
public CardUtils() {
}
public static ArrayList<Ingredient> readIngredientFile(String path){
ArrayList<Ingredient> ingredients = new ArrayList<Ingredient>(); //hold the ingredients from the file
try{
FileReader file = new FileReader(path);
BufferedReader reader = new BufferedReader(file);
String line;
while((line = reader.readLine()) != null){
if (line.equals("NAME, COUNT")){
reader.readLine();
continue;
}
ArrayList<Ingredient> ingredient = stringToIngredient(line);
for (int i = 0; i < ingredient.size(); i++){
ingredients.add(ingredient.get(i));
}
}
reader.close();
System.out.println(ingredients);
System.out.println(ingredients.size());
return ingredients;
} catch (FileNotFoundException e){
System.err.println("File not found: " + path);
return ingredients;
} catch (IOException e){
e.printStackTrace();
return ingredients;
}
}
public static ArrayList<Ingredient> stringToIngredient(String str){
String[] parts = str.split(",");
ArrayList<Ingredient> ingredients = new ArrayList<Ingredient>(); //hold the ingredients from the line
int quantity;//maybe erase
//error handling
if(parts.length != 2){
System.err.println("Invalid ingredient string: " + str);
return null;
}
else{
String name = parts[0].trim();
if (parts[1].trim().matches("\\d+")){
quantity = Integer.parseInt(parts[1].trim());
}
else{
System.err.println("Invalid ingredient string: " + parts[1].trim());
return null;}
//int quantity = Integer.parseInt(parts[1].trim());
for (int i = 0; i < quantity; i++){
Ingredient ingredient = new Ingredient(name);
ingredients.add(ingredient);
}
return ingredients;
}
}
}
コードにより、次のエラーメッセージが表示されます。
Exception in thread "main" java.lang.NumberFormatException: For input string: "COUNT"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.base/java.lang.Integer.parseInt(Integer.java:652)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at util.CardUtils.stringToIngredient(CardUtils.java:55)
at util.CardUtils.readIngredientFile(CardUtils.java:24)
at bakery.MagicBakery.<init>(MagicBakery.java:34)
at BakeryDriver.main(BakeryDriver.java:9)
正文到此结束
- 本文标签: 家庭宠物
- 本文链接: https://www.coder6.net/article/2546
- 版权声明: 本文由蚂蚁原创发布,转载请遵循《署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)》许可协议授权
热门推荐
-
浏览(193) 评论(0)