Java中Scanner的next和nextLine的使用以及区别

Scanner实现字符串的输入的两种方法:一是next(),另一种则是nextLine(),下面通过代码实例看看两者的区别:

package SwordOffer;

import java.util.Scanner;

/**
 * Created by L_kanglin on 2017/3/14.
 * 区分next和nextLine
 */
public class TestNextAndNextLine {
    public static void main(String[] args){
        Scanner sc=new Scanner(System.in);
        TestNextLine(sc);
    }
    public static void TestNext(Scanner sc){
        String str1=sc.next();
        System.out.println("str1:"+str1);
    }
    public static void TestNextLine(Scanner sc){
        String str2=sc.nextLine();
        System.out.println("str2:" +str2);
    }
}

next的测试:

abc def
str1:abc

nextLine的测试:

abc def
str2:abc def

由上述的结果,可以得到:
next()对输入有效字符之前遇到的空格键、Tab键或Enter键等结束符,next()方法会自动将其去掉,只有在输入有效字符后,next()方法才将其后输入的空格键、Tab键或Enter键等视为分隔符或者结束符,所以next()方法读取的是不能带空格的字符串。
nextLine()方法的结束符只是Enter键,即nextLine()方法返回的是Enter键之前的所有字符,它是可以得到带空格的字符串的。

注意一下情况,就是两者一起用:

import java.util.Scanner;

/**
 * Created by L_kanglin on 2017/3/14.
 * 区分next和nextLine
 */
public class TestNextAndNextLine {
    public static void main(String[] args){
        Scanner sc=new Scanner(System.in);
        TestNext(sc);
    }
    public static void TestNext(Scanner sc){
        String str1=sc.next();
        String str3=sc.nextLine();
        System.out.println("str1:"+str1);
        System.out.println("str3:"+str3);
    }
    public static void TestNextLine(Scanner sc){
        String str2=sc.nextLine();
        System.out.println("str2:" +str2);
    }
}

测试如下:

abc def
str1:abc
str3: def

此时str3的是接上一个输入值来的,使用nextLine,可以读取空格值。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值