我当前在循环中遇到问题。输入一次字符串后,它会提示用户,并且在满足循环条件时,它只会不断询问用户“是否要继续?”并且无法输入其他字符串。
public static void main(String[] args) throws IOException
{
BufferedReader bfr = new BufferedReader(new InputStreamReader(System.in));
LinkedList<String> strList = new LinkedList();
char choice;
do
{
System.out.print("Add Content: ");
strList.add(bfr.readLine());
System.out.print("Do you want to add again? Y/N?");
choice = (char)bfr.read();
}
while(choice == 'Y');
}
通常,只有在您按下Enter键后,终端才会发送数据。因此,当您再次执行readLine
时,您会得到一个空行。您必须阅读一行,然后检查它是否包含Y
。或之后再读空行,以您认为不太容易出错的方式为准。
我倾向于使用较早版本并阅读完整的行,然后检查其中包含的内容。
您需要从键盘缓冲区中取出换行符。您可以这样做:
do
{
System.out.print("Add Content: ");
strList.add(bfr.readLine());
System.out.print("Do you want to add again? Y/N?");
//choice = (char)bfr.read();
choice = bfr.readLine().charAt(0); // you might want to check that a character actually has been entered. If no Y or N has been entered, you will get an IndexOutOfBoundsException
}
while(choice == 'Y');