Scanner(System.in) 关于cache清空的问题

ImAmelie 2017-07-04 12:54:08

import java.util.Scanner;
//输入一个数,显示一个数,输入错误重新输入
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double temp;
while (true) {
System.out.print("输入:");//输入一个数
while (!sc.hasNextDouble()) {//如果输入的不是数字,进入循环
System.out.print("输入错误,重新输入:");
sc.nextLine();//释放掉输入内容
}
temp = sc.nextDouble();//在输入正确的情况下接受数字
System.out.println(temp);
}
}
}



我的输入操作:



输入
45 asdf asdf sad fdsaf 1212
temp接受45
在接受45后Scanner里有缓存"asdf asdf sad fdsaf 1212"
之后重新进入外循环
控制台打印"输出"
进行内循环条件判断
因为Scanner有cache,"asdf asdf sad fdsaf 1212"所以直接显示输入错误,重新输入:

有没有什么办法可以在不确定cache有没有内容的情况下直接清空cache?
比如sc.nextLine()
在cache有内容的情况下就会直接清除内容
但是cache没有值的情况下,程序会挂起来等待用户输入(※)
有没有什么办法可以实现类似C语言的fflush()函数(不管输入直接清空输入流)功能?
...全文
606 5 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
再不斩 2017-10-13
  • 打赏
  • 举报
回复

Scanner sc = new Scanner(System.in);
        double temp;
        while (true) {
            System.out.print("输入:");//输入一个数
            while (!sc.hasNextDouble()) {//如果输入的不是数字,进入循环
                String line= sc.nextLine();//释放掉输入内容
                if(line.isEmpty())
                    break;
                try {
					Double.parseDouble(line);
				} catch (Exception e) {
					break;
				}
                System.out.println();
                System.out.print("输入错误,重新输入:");
            }
            temp = sc.nextDouble();//在输入正确的情况下接受数字
            System.out.println(temp);
        }
xiaovhao 2017-07-05
  • 打赏
  • 举报
回复
你可以确定他有没有内容的啊,sc.hasNext()
ImAmelie 2017-07-05
  • 打赏
  • 举报
回复
引用 2 楼 zaibuzhankkk 的回复:

Scanner sc = new Scanner(System.in);
        double temp;
        while (true) {
            System.out.print("输入:");//输入一个数
            while (!sc.hasNextDouble()) {//如果输入的不是数字,进入循环
            	String line= sc.nextLine();//释放掉输入内容
            	if(line.isEmpty())
            		continue;
                System.out.print("输入错误,重新输入:");
            }
            temp = sc.nextDouble();//在输入正确的情况下接受数字
            System.out.println(temp);
        }
特别感谢你的回答,但是你的代码运行后也解决不了我的问题
再不斩 2017-07-05
  • 打赏
  • 举报
回复

Scanner sc = new Scanner(System.in);
        double temp;
        while (true) {
            System.out.print("输入:");//输入一个数
            while (!sc.hasNextDouble()) {//如果输入的不是数字,进入循环
            	String line= sc.nextLine();//释放掉输入内容
            	if(line.isEmpty())
            		continue;
                System.out.print("输入错误,重新输入:");
            }
            temp = sc.nextDouble();//在输入正确的情况下接受数字
            System.out.println(temp);
        }
HinanaiTenshi 2017-07-05
  • 打赏
  • 举报
回复
在输入正确的情况下接受数字 虽然你注释是这么写的,然而实际执行的时候无论是否正确,这条语句必定被执行

62,634

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧