package com.ethjava; import java.util.Scanner; public class hasnextlizi { public static void main(String[] args){ Scanner sc=new Scanner(System.in); String input=null; /* input=sc.next(); System.out.println(input); //sc.nextLine(); input=sc.nextLine(); System.out.println(input); sc.close(); System.out.println(input.length()); */ //在运行nextLine()时我想再次输入,但是它读取了next()剩下的回车。当在sc.next()后面加一个sc.nextLine()即可消除该回车。 //当你输入一串带空格的字符串,敲下回车后,若最开始碰到sc.next(),sc.next()只会读取第一个不是空格的单词。 // 例如,当sc.next读完hello后,读取的cursor是在空格前,导致读取的nextLine长度是6。 /* 第二部分:遇到hasNext()时,Scanner也会阻塞,等待你输入,等你输入后返回true。 查看jdkapi,你会发现该方法当Scanner缓存区中有值可读时,会返回true, 若没有,会一直阻塞等待你输入。 当我们想退出用hasNext作条件的while()循环时,那么要么控制台手工输入ctrl+z,要么 while(!sc.hasNext("#"))约定当一行输入#时退出。 */ /* boolean hasnext=sc.hasNext(); System.out.println(hasnext); while(!sc.hasNext("#")){ System.out.println("请输入"); input =sc.nextLine(); System.out.println(input); } sc.close(); System.out.println(input.length()); */ int input2; while(true){ if(sc.hasNextInt()){ input2 = sc.nextInt(); break; }else{ System.out.println("请输入数字"); sc.next();//实现hasNextInt的读取的标记位置的改变 } } System.out.println("输入的数字是:"+input2); //hasNextInt()函数大体意思表示scanner当前的标记的输入是否为int,并不会自动的移动标记。 //例如实现一个判断当前到输入是否为数字,不是的话提示输入数字。若是以下代码:当输入的不是数字时,会一直输出请输入 //要实现hasNextInt的读取的标记位置的改变,可以用scanner.next()移动。 } }
参考:
https://blog.csdn.net/weixin_41262453/article/details/88815173?utm_source=app