gpt4 book ai didi

java - BufferedReader.nextLine() 不会前进到下一行,所以我陷入了循环

转载 作者:行者123 更新时间:2023-12-02 00:38:49 24 4
gpt4 key购买 nike

我正在尝试重用 Scanner(System.in)BufferedReader(FileReader) 的输入方法。当用户输入“readfile”作为命令时,程序将文件中的第一个人(即文件中的第一行)添加到列表中,但 BufferedReader 被卡在同一行上,并且因此陷入了无限循环。
键盘输入的 Scanner 方法就像一个魅力。

    class Menu {
public static final int ARRAYINDEXFOREMAIL = 3;
private static final String NEWPERSON = "newperson";
private static final String FROMFILE = "readfile";
public static final String READFILE = "saved.txt";
private Scanner keyboardInput = new Scanner( System.in );
private String name;
private String tlf;
private String[] email;
private String [] stringTmp;
private String in;
private boolean readFromFile = false;

Menu( boolean fileRead ) {
if( fileRead ) {
readFromFile = true;
}
else {
readFromFile = false;
}
}

void run() {
while(true) {
System.out.print("\n" + "ordre> ");
if ( !readFromFile ) {
in = keyboardInput.nextLine();
}
else {
try {
BufferedReader fileOut = new BufferedReader(
new FileReader( READFILE ) );
if( ( in = fileOut.readLine() ) == null ) {
readFromFile = false;
fileOut.close();
break;
}
else {
System.out.println("in stringTmp is: " + in); // For debugging purposes
}
}
catch (FileNotFoundException filenotfoundexception) {
System.out.println("Cannot find file: " + READFILE + " !");
}
catch (IOException ioexception) {
ioexception.printStackTrace();
}
}
stringTmp = in.split("\\s+");

if( stringTmp[0].equalsIgnoreCase(NEWPERSON) ) {
if( stringTmp.length <= 1 ) {
System.out.println("ERROR! Enter one or more parameters..");
continue;
}
else {
name = stringTmp[1];
tlf = stringTmp[2];
if( stringTmp.length > ARRAYINDEXFOREMAIL ) {
email = new String[stringTmp.length - ARRAYINDEXFOREMAIL];

for( int i = ARRAYINDEXFOREMAIL, j = i - ARRAYINDEXFOREMAIL ; i < stringTmp.length; i++, j++ ) {
email[j] = stringTmp[i];
}
}
else {
email = new String[0];
}
mainlist.addPerson( name, tlf, email );
}
}

else if ( stringTmp[0].equalsIgnoreCase(FROMFILE) ) {
Meny m = new Menu( true );
m.run();
}
}
}
}

最佳答案

请注意,在循环本身中您设置了

BufferedReader fileOut = new BufferedReader(new FileReader( READFILE ) );

这将导致创建一个新的BufferedReader!
在循环的下一次迭代中 - 您将重复此行,并重置 fileOut 作为结果 - 当您调用 fileOut.readLine() 时 - 它将读取再次第一行。

您应该在循环之前初始化 fileOut,而不是在循环中来解决这个问题。

关于java - BufferedReader.nextLine() 不会前进到下一行,所以我陷入了循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9312170/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com