Java的next()和nextLine()

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

 

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

:class

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+"*");
  }
}import

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

输出:*AB*CD*im

 

2.nextLine方法的结束符只是Enter键,即nextLine方法返回的是在输入Enter键以前的全部内容。next

:  static

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+"*");
  }
}word

输入: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.

相关文章
相关标签/搜索