java 如何清除java中的输入缓冲区

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30985691/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 17:55:40  来源:igfitidea点击:

how to clear input buffer in java

javabuffer

提问by ANUPAM CHANDA

For avoiding any unwanted character which has been entered in console like \n

避免在控制台中输入任何不需要的字符,如\n

we use nextInt()or nextLine()etc.

我们使用nextInt()nextLine()等。

But in these cases actually the control is going a step ahead leaving the unwanted string or something like this. But I want to delete or flush out the memory of bufferin which other unwanted data is taken by the system. For example -->

但在这些情况下,实际上控件会提前一步留下不需要的字符串或类似的东西。但是我想删除或清除系统获取其他不需要的数据的缓冲区的内存。例如-->

Scanner scan=new Scanner(System.in);
scan.nextInt();
scan.nextline();//this statement will be skipped

becausethe system is taking \nas a line next to the integer given as input. In this case without using scan.nextLine()I want to simply clear/flush out the buffer memory where the \nwas stored. Now please tell me how to delete the input buffer memory in java

因为系统将\n作为输入的整数旁边的一行。在这种情况下,不使用scan.nextLine()我只想清除/刷新存储\n的缓冲存储器。现在请告诉我如何在java中删除输入缓冲内存

Thank you. :)

谢谢你。:)

回答by Pieter12345

You can use this to clear all existing data in the buffer:

您可以使用它来清除缓冲区中的所有现有数据:

while(sc.hasNext()) {
    sc.next();
}

If you are only doing this to remove the newline (\n) characters from the input, you can use:

如果您只是为了从输入中删除换行符 (\n) 字符,则可以使用:

while(sc.hasNext("\n")) {
    sc.next();
}

If the goal is to only read integers and skip any other characters, this would work:

如果目标是只读取整数并跳过任何其他字符,这将起作用:

while(sc.hasNext() && !sc.hasNextInt()) {
    sc.next();
}