我不确定为什么我使用“\ |”会出现“无效的转义序列”错误,因为它应该只是使它成为一个|字符?我正在尝试读取文件,其中值由|分隔角色,由于某种原因,它给了我一个非常奇怪的输出。我有一个文本文件:
Star Trek|Sci-fi|Sy-fy|48|is
Word Girl|Children's|PBS Kids|21|is
Firefly|Sci-fi|FOX|50|is
America's Next Top Model|Drama|CNN|51|is not
Being Human|Sci-fi|Sy-fy|48|is not
Black Mirror|Anthology|Channel 4|55|is
Grandma's House|Comedy|BBC Two|26|is
Sherlock|Crime drama|BBC One|55|is
Psych|Comedy-Drama|ION|51|is not
The Big Bang Theory|Sitcom|CBS|23|is not
我想逐行浏览这个文本文件,然后通过电视节目类传递它,如下所示:
public class TVShows {
private String showName;
private String genre;
private String network;
private String favourite;
private String runningTime;
public TVShows(String showName, String genre, String network, String favourite, String runningTime){
this.genre = genre;
this.showName = showName;
this.network = network;
this.runningTime = runningTime;
this.favourite = favourite;
}
public String toString(){
return showName + ", on " + network + ", a " + genre + " show with a running time of " + runningTime + " minutes. This "
+ favourite + " a favourite.";
}
}
这一切都非常简单,但出于某种原因,当我在驱动程序中实现它时,就在这里:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Driver {
public static void main(String[] args) throws FileNotFoundException {
File myFile = new File("./src/TVShows.txt");
Scanner fileScanner = new Scanner(myFile);
while(fileScanner.hasNextLine())
{
TVShows myShows = new TVShows("test","test","test","test","test");
String line = fileScanner.nextLine();
System.out.println(fileScanner.nextLine());
Scanner lineScanner = new Scanner(line);
lineScanner.useDelimiter("\|");
while(lineScanner.hasNext())
{
System.out.println(lineScanner.next());
String showName = lineScanner.next();
String genre = lineScanner.next();
String network = lineScanner.next();
String runningTime = lineScanner.next();
String favourite = lineScanner.next();
TVShows myShows1 = new TVShows(showName, genre, network, favourite, runningTime);
System.out.println(myShows1);
}
}
}
}
我在“\ |”上遇到无效的转义序列错误。为什么是这样?我只需要添加另一个反斜杠吗?喜欢“\ |”?当我这样做,并运行该程序时,我得到输出:
ÿþS t a r T r e k
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at Program3.Driver.main(Driver.java:30)
这是第30行:
String favourite = lineScanner.next();
感谢您的帮助。
答案 0 :(得分:0)
你应该在java中使用两个反斜杠
lineScanner.useDelimiter("\\|");
答案 1 :(得分:0)
你需要两个反斜杠:
lineScanner.useDelimiter("\\|");
第一个是从编译器中解析第二个。它们一起在字符串常量中生成一个反斜杠,用于转义正则表达式引擎中的管道符号。
答案 2 :(得分:0)
这部分代码
while(lineScanner.hasNext())
{
System.out.println(lineScanner.next());
String showName = lineScanner.next();
String genre = lineScanner.next();
String network = lineScanner.next();
String runningTime = lineScanner.next();
String favourite = lineScanner.next();
}
包括检查hasNext()
一次,然后再运行next()
六次。因此,如果您有多个元素不能被6整除,那么您将不可避免地剩下一些n<6
个元素,获取n
元素,然后在尝试获取{{1}时出错元素。
从您的数据中,我假设您应该有5个元素,而不是6.我猜测您的n+1
通过请求额外元素来破坏流量。在您定义println
后,将其删除并在某处添加System.out.println(showName);
;这应该可以解决你的问题。