next() 与 nextLine()的区别

next() :
一定要读到有效字符之后才可以结束输入,对于输入有效字符之前遇到的空格键,tab键,enter键为结束的,next()都将自动去掉。next()方法将输入有效字符之后的空格键,tab键,enter键作为结束符。next()读取字符串的时候不能读到空格。

nextLine() :
结束符为enter,输入字符中可以带有空格。

下面是几个有关上述两个函数的例子 :
1.

import java.util.*;
public class Main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Scanner s = new Scanner(System.in);
         String s1 , s2 , s3;
         s1 = s.next();
         System.out.println("这是s1的输出结果 : " + s1);
         s2 = s.nextLine();
         System.out.println("这是s2的输出结果 : " + s2);
         s3 = s.next();
         System.out.println("这是s3的输出结果 : " + s3);

         s.close();
    }
}

上面代码的输出结果如下 :

这是第一次输入
这是s1的输出结果 : 这是第一次输入
这是s2的输出结果 : 
这是第二次输入
这是s3的输出结果 : 这是第二次输入

在s2输出时,s2的nextLine()自动读取第一次输入被舍弃的enter作为结束符,所以s2的输出为空,因此在上面的代码中只有两次输入。

2.

import java.util.*;
public class Main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Scanner s = new Scanner(System.in);
         String s1 , s2 , s3;
         s1 = s.nextLine();
         System.out.println("这是s1的输出结果 : " + s1);
         s2 = s.nextLine();
         System.out.println("这是s2的输出结果 : " + s2);
         s3 = s.nextLine();
         System.out.println("这是s3的输出结果 : " + s3);

         s.close();
    }
}

上述代码的输出结果如下 :

这是第一次输入
这是s1的输出结果 : 这是第一次输入
这是第二次输入
这是s2的输出结果 : 这是第二次输入
这是第三次输入
这是s3的输出结果 : 这是第三次输入

本次的输入次数为3次,每次输入以enter键作为结束,每次输入出现一个输出结果。

3.

import java.util.*;
public class Main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Scanner s = new Scanner(System.in);
         String s1 , s2 , s3;
         s1 = s.next();
         s.nextLine();
         System.out.println("这是s1的输出结果 : " + s1);
         s2 = s.nextLine();
         System.out.println("这是s2的输出结果 : " + s2);
         s3 = s.nextLine();
         System.out.println("这是s3的输出结果 : " + s3);

         s.close();
    }
}

上述代码的输出结果为 :

这是第一次输入
这是s1的输出结果 : 这是第一次输入
这是第二次输入
这是s2的输出结果 : 这是第二次输入
这是第三次输入
这是s3的输出结果 : 这是第三次输入

此次输入也为三个,这个例子说明,可以在next(),nextInt(),nextDouble(),nextFloat()等后加上一个nextLine(),用来将next(),nextInt(),nextDouble(),nextFloat()等函数舍弃的enter键过滤掉。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值