hasNext()用法

21 篇文章 0 订阅
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

 

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值