how to clear input buffer in java

耗尽温柔 提交于 2019-12-23 06:08:16

问题


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

we use nextInt() or nextLine() etc.

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 buffer in 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

because the system is taking \n as 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 \n was stored. Now please tell me how to delete the input buffer memory in java

Thank you. :)


回答1:


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:

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();
}


来源:https://stackoverflow.com/questions/30985691/how-to-clear-input-buffer-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!