到目前为止,我有一个文本文件,如下所示:
// this is a comment, any lines that start with //
// (and blank lines) should be ignored
[ElectricTool data]
// data is rechargeable, power, timesBorrowed, onLoan, toolName, itemCode, cost, weight
true,18V,12,false,Makita BHP452RFWX,RD2001,14995,1800
etc...
以及以下代码来浏览此文本文件:
public void readData()
{ try{
FileDialog fileDialogBox = new FileDialog(myFrame, "Open", FileDialog.LOAD);
fileDialogBox.setVisible(true);
String fileName = fileDialogBox.getFile();
File dataFile = new File(fileName);
Scanner scanner = new Scanner(dataFile);
String lineOfText;
String typeOfData="";
while(scanner.hasNext())
{
lineOfText = scanner.nextLine().trim();
ElectricTool electricTool = new ElectricTool();
if (lineOfText.startsWith("[ElectricTool data]")){
typeOfData="ElectricTool";
}
else if (!lineOfText.isEmpty() ){
if (!lineOfText.startsWith("//")){
if ( typeOfData.equals("ElectricTool")){
Scanner sc = new Scanner(lineOfText).useDelimiter(",");
electricTool.extractTokens(sc);
toolList.add(electricTool);
itemCount++;
sc.close();
}
}
}
}
scanner.close();
}
catch(FileNotFoundException ex)
{
System.out.println("ERROR: File NOT Found! ");
}
}
有问题的方法:
public void extractTokens(Scanner sc)
{
recheargable = sc.nextBoolean();
power = sc.next().trim();
super.extractTokens(sc);
}
recheargable声明为布尔值: private boolean recheargable;
当它到达recharge = sc.nextBoolean()时,它给出了missmatch异常; 也许问题出现在readData方法的if语句中?我试图重做if语句,但它没有用。任何想法如何修复错配?
答案 0 :(得分:0)
我想验证并创建以下测试:
public static void main(String[] args) {
Scanner sc = new Scanner("true,18V,12,false,Makita BHP452RFWX,RD2001,14995,1800").useDelimiter(",");
if (sc.hasNext()) {
try {
System.out.println(sc.nextBoolean());
} catch (Exception e) {
System.err.println(sc.next());
}
}
while (sc.hasNext()) {
System.out.println(sc.next());
}
}
它的工作应该是,我会改变代码如下以确定问题
public void extractTokens(Scanner sc) {
try {
recheargable = sc.nextBoolean();
} catch (Exception e) {
System.err.println("troublemaker: " + sc.next());
}
power = sc.next().trim();
super.extractTokens(sc);
}
编辑#1: 根据你的回答,我无法确认,你可能想尝试一些更多的错误检测。我想你的问题是另一个问题。
public void extractTokensx(Scanner sc) {
try {
recheargable = sc.nextBoolean();
power = sc.next().trim();
super.extractTokens(sc);
} catch (Exception e) {
System.err.println("dumping the rest of the troubeling line: ");
while (sc.hasNext()) {
System.err.print(sc.next() + " - ");
}
}
}