next与nextline注意事项

使用注意

1. Scanner.nextLine()是会读取控制台的所有内容字符,包括敲下回车键产生的结束符。而其他录入方式在读取到录入的有效内容之前,所有的无效内容会自动跳过(例如空格,Tab键,回车键等产生的无效字符)。所以当之前使用过其他录入方式,录入结束后Enter产生的结束符会留在控制台,此时使用Scanner.nextLine()就会直接接收这个结束符,导致录入直接结束

2.

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("使用next方式接收:");
    if (scanner.hasNext()){
        String str1 = scanner.next();
        System.out.println("输出内容为:"+str1);
    }
    System.out.println("==================================");
    System.out.println("使用next方式接收:");
    if (scanner.hasNext()){
        String str2 = scanner.next();
        System.out.println("输出内容为:"+str2);
    }
    scanner.close();
}
/*
输出结果
使用next方式接收:
hello world
输出内容为:hello
==================================
使用nextLine方式接收:
输出内容为: world
*/
public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("使用nextLine方式接收:");//输入时直接输入回车代码就会继续运行
    if (scanner.hasNextLine()){
        String str1 = scanner.nextLine();
        System.out.println("输出内容为:"+str1);
    }
    System.out.println("==================================");
    System.out.println("使用nextLine方式接收:");
    if (scanner.hasNextLine()){
        String str2 = scanner.nextLine();
        System.out.println("输出内容为:"+str2);
    }
    scanner.close();
}
/*
输出结果
使用nextLine方式接收:
hello world
输出内容为:hello world
==================================
使用nextLine方式接收:
hello world
输出内容为:hello world
*/
public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("使用next方式接收:");
    if (scanner.hasNext()){
        String str1 = scanner.next();
        System.out.println("输出内容为:"+str1);
    }
    System.out.println("==================================");
    System.out.println("使用nextLine方式接收:");
    if (scanner.hasNextLine()){
        String str2 = scanner.nextLine();
        System.out.println("输出内容为:"+str2);
    }
    scanner.close();
}
/*
输出结果
使用next方式接收:
hello world
输出内容为:hello
==================================
使用nextLine方式接收:
输出内容为: world
*/

如果键盘输入的东西没有用完(如中途因为空格停止例第一个代码)且后面还有要求输入数值才能继续进行的语句,则会优先用之前输入没用完的,此时会出现跳过再次输入的情况(前提只创建了一次Scanner对象)(其它类型的next好像也这样)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值