如何清除Java中的输入缓冲区 [英] how to clear input buffer in java

查看:769
本文介绍了如何清除Java中的输入缓冲区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

但是在这些情况下,控件实际上向前走了一步,留下了不需要的字符串或类似内容。
但是我想删除或清除 buffer 的内存,系统会在其中删除其他不需要的数据。
例如->

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

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

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

谢谢。 :)

推荐答案

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

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

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

如果仅这样做是为了删除换行符(\n)从输入中,您可以使用:

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

这篇关于如何清除Java中的输入缓冲区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆