Java的next()和nextLine()

0.next和nextLine是Scanner类中的两个方法。

 

1.next方法只接收有效字符。在遇到有效字符之前,输入的空格键,Enter键和Tab键等键,next方法都会忽略掉它们。遇到有效字符后,则遇到这些键退出。

:

import java.util.*;
public class ITest1
{
  public static void main(String[] args)
  {
    Scanner in=new Scanner(System.in);
    String text1=in.next();
    String text2=in.next();
    System.out.println("*"+text1+"*"+text2+"*");
  }
}

输入:Tab键AB空格键空格键CD空格键Enter键

输出:*AB*CD*

 

2.nextLine方法的结束符只是Enter键,即nextLine方法返回的是在输入Enter键之前的所有内容。

:  

import java.util.*;
public class ITest2
{
  public static void main(String[] args)
  {
    Scanner in=new Scanner(System.in);
    String text=in.nextLine();
    System.out.println("*"+text+"*");
  }
}

输入:AB空格键CDEnter键

输出:*AB CD*

 

3.next和nextLine方法连用

:

import java.util.*;
public class ITest3
{
  public static void main(String[] args) 
  {

    Scanner in=new Scanner(System.in);
    String text1=in.nextLine();
    String text2=in.next();
    System.out.println(text1);
    System.out.println(text2);

 

  }
}

输入:Tom and JerryEnter键cartoonEnter键

输出:Tom and Jery

   cartoon

但是如果交换next和nextLine的顺序

:

import java.util.*;
public class ITest4
{
  

public static void main(String[] args)
  {
    Scanner in=new Scanner(System.in);
    System.out.println("Enter first word");
    String text1=in.next();
    System.out.println("Enter second word");
    String text2=in.nextLine();
    System.out.println(text1+"*"+text2);
  }

}

 

输入1:

Enter first word

my name isEnter键

输出1:

Enter second word

my* name is

 

输入2:

Enter first word

myEnter键

输出2:

Enter second word

my*

为什么会出现这种错误呢?

 前面说过,next在读取到了有效字符(my)之后,自然地将后面出现的Enter键视为结束符。但是后面的nextLine方法读取了有效字符my之后的所有字符包括Enter键(即nextLine把输入给next的Enter键当作了它自己的结束符)。因此,在输入1中,nextLine读取了 name isEnter键;在输入2中,nextLine读取了Enter键。所以Text2无法从键盘上获得输入值。

不仅是next方法,nextInt、nextDouble等方法与nextLine方法连用时都会产生这种问题。但nextLine和nextLine连用时不会出现这种问题。

解决方法:

可以在next方法后再加入一个nextLine方法,让它读取掉输入给next的Enter键,这样下一个nextLine就可以从键盘上得到输入的内容。

import java.util.*;
public class ITest4
{

public static void main(String[] args) 
  {

    Scanner in=new Scanner(System.in);
    System.out.println("Enter first word");
    String text1=in.next();
    in.nextLine();
    System.out.println("Enter second word");
    String text2=in.nextLine();
    System.out.println(text1+"*"+text2);

  }

}

输入:

Enter first word

My name isEnter键

Enter second word

age is 30.Enter键

输出:My*age is 30.

转载于:https://www.cnblogs.com/EdwardChu/p/5836268.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值