提问人:steveee26 提问时间:2/11/2020 更新时间:2/11/2020 访问量:625
Java BufferedReader readLine() 在 read() 之后突然不工作
Java BufferedReader readLine() suddenly not working after read()
问:
我目前的循环有问题。在我输入一个字符串后,它会提示用户,当满足循环条件时,它只是不断询问用户“你想继续吗?”,并且无法输入另一个字符串。
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');
}
答:
0赞
Maarten Bodewes
2/11/2020
#1
通常,终端仅在您按回车键后发送数据。所以当你再次表演时,你会得到一个空行。您必须阅读一行,然后检查它是否包含。或者事后阅读空行,以您认为不容易出错的为准。readLine
Y
我倾向于使用前面的并阅读一整行,然后检查它包含的内容。
1赞
ControlAltDel
2/11/2020
#2
您需要从键盘缓冲区中取出换行符。你可以这样做,就像这样:
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');
0赞
Themelis
2/11/2020
#3
不要忘记,对于像这个程序这样简单的事情,您可以使用方便的类。java.io.Console
Console console = System.console();
LinkedList<String> list = new LinkedList<>();
char choice = 'N';
do {
System.out.print("Add Content: ");
list.add(console.readLine());
System.out.print("Do you want to add again? Y/N?\n");
choice = console.readLine().charAt(0);
} while (choice == 'Y' || choice == 'y');
0赞
Belluzzo Matteo
2/11/2020
#4
这部作品(别忘了图书馆):
public static void main(String[] args) throws IOException
{
BufferedReader bfr = new BufferedReader(new InputStreamReader(System.in));
List<String> strList = new ArrayList<String>();
String choice;
do {
System.out.println("Add Content: ");
strList.add(bfr.readLine());
System.out.println("Do you want to add again? Y/N?");
choice = bfr.readLine();
} while(choice.equals("Y"));
System.out.println("End.");
}
0赞
Pandey Praveen
2/11/2020
#5
试试这个:
public static void main(String[] args) throws IOException
{
Scanner scan=new Scanner(System.in);
LinkedList<String> strList = new LinkedList();
String choice;`
do
{
System.out.print("Add Content: ");
strList.add(scan.nextLine());
System.out.print("Do you want to add again? Y/N?");
choice = scan.nextLine();
}
while(choice.equals("Y"));
}
评论
Y
readLine
Scanner