我正在尝试打印一个演员列表,该程序正在打印所有名称但我收到错误。我需要帮助找到一种方法来打印程序将在姓氏之后结束while循环的名称。
以下是清单:
Leonardo Dicaprio
Susan Sarandon
Tom Hanks
Robert De Niro
Barack Obama
Helen Keller
Katharine Cornell
Helen Hayes
John Laughlin
Mark Zuckerberg
Joe Lipari
Welker White

这是我的计划:
public void printActors()
throws FileNotFoundException
{
Scanner input = new Scanner(new File("actors"));
String line = null;
while ((line = input.nextLine()) != null)
{
System.out.println(line);
}
}

这是输出:
Leonardo Dicaprio
Susan Sarandon
Tom Hanks
Robert De Niro
Barack Obama
Helen Keller
Katharine Cornell
Helen Hayes
John Laughlin
Mark Zuckerberg
Joe Lipari
Welker White
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at Game.BaconGame.main(BaconGame.java:26)

有人可以帮助我这样它可以打印列表上的名字并摆脱错误吗?
答案 0 :(得分:2)
使用while (input.hasNextLine())
检查输入流中是否存在行(如果找不到行,则Scanner
不会返回null
,它会抛出NoSuchElementException
)< / p>
如果您只想阅读文件而不是解析,我强烈建议您使用FileReader
和BufferedReader
。
答案 1 :(得分:0)
FileReader in = new FileReader("actors");
BufferedReader br = new BufferedReader(in);
String line=br.readLine() ;
while (line != null) {
System.out.println(line);
line=br.readLine() ;
}
in.close();
或根据您的代码
Scanner input = new Scanner(new File("actors"));
while ((input.hasNextLine()))
{
System.out.println(input.nextLine());
}
答案 2 :(得分:0)
请尝试以下代码:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Test {
public static void main(String[] args) {
BufferedReader bufferedReader = null;
try {
String line;
bufferedReader = new BufferedReader(new FileReader("actors"));
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bufferedReader != null)
bufferedReader.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
答案 3 :(得分:0)
public void printActors() throws FileNotFoundException
{
Scanner input = new Scanner(new File("c:\\actors.txt"));
while(input.hasNextLine())
{
System.out.println(input.nextLine());
}
}