此程序使用逗号分隔文本元素访问文本文件。元素注册在我创建的变量中。除了最后一个。然后就会发生错误。该程序与扫描器类的默认空格分隔符(文本文件被默认调整)很好地工作,但当我使用逗号作为分隔符时,程序会失败。有谁能提供一些洞察力。
文本数据:
smith,john,10
stiles,pat,12
mason,emrick,12代码:
public void openFile(String f)
{
try{
x = new Scanner(new File(f));
x.useDelimiter(",");
} catch(Exception e){
System.out.println("File could not be found please check filepath");
}
}
public boolean checkNameRoster()
{
openFile(file);
boolean b = false;
while(x.hasNext())
{
String lName = x.next().trim();
**String fName = x.next().trim();**
String grade = x.next().trim();
if(fName.equalsIgnoreCase(firstName) && lName.equalsIgnoreCase(lastName) && grade.equalsIgnoreCase(grade))
{
b = true;
}
}
closeFile();
return b;
}发布于 2017-09-04 20:02:39
这个问题取决于您在函数x.useDelimiter(",");中的Scanner上调用了openFile()。
由于您的文本数据是:
smith,john,10
stiles,pat,12
mason,emrick,12Scanner将其视为:
"smith,john,10\nstiles,pat,12\nmason,emrick,12"所以,当您执行代码时会发生什么情况:
1: x.hasNext() ? Yes
x.next().trim() => "smith"
x.next().trim() => "john"
x.next().trim() => "10\nstiles"
2: x.hasNext() ? Yes
x.next().trim() => "pat"
x.next().trim() => "12\nmason"
x.next().trim() => "emrick"
3: x.hasNext() ? Yes
x.next().trim() => "12"
x.next().trim() => Error!要解决这个问题,您可以编辑文件并使用,更改所有,,或者使用第一个Scanner获取所有行,另一个使用Scanner获取令牌,如下所示:
public void openFile(String f)
{
try{
x = new Scanner(new File(f)); // Leave default delimiter
} catch(Exception e){
System.out.println("File could not be found please check filepath");
}
}
public boolean checkNameRoster()
{
openFile(file);
boolean b = false;
while(x.hasNextLine()) // For each line in your file
{
Scanner tk = new Scanner(x.nextLine()).useDelimiter(","); // Scan the current line
String lName = x.next().trim();
String fName = x.next().trim();
String grade = x.next().trim();
if (fName.equalsIgnoreCase(firstName) && lName.equalsIgnoreCase(lastName) && grade.equalsIgnoreCase(grade))
{
b = true;
}
}
closeFile();
return b;
}https://stackoverflow.com/questions/40209754
复制相似问题