天天看點

Java Scanner next()和nextLine()的差別

Java Scanner next()和nextLine()的差別

Scanner簡單介紹:

Scanner的用途廣泛,而且好用,它自身包含了很多構造方法,可以接收各種類型資料,可以是一個檔案、輸入流、控制台……

Scanner為我們提供了很多的方法以使用,其中有兩個方法next()和nextLine(),這兩個方法傳回的都是String類型的,那麼為什麼要有兩個功能類似的方法,它們的差別又在哪裡呢?

next()特點:

1、一定要讀取到有效字元後才可以結束輸入,

2、對輸入有效字元之前遇到的空白,next()方法會自動将其去掉,

3、隻有輸入有效字元後才将其後面輸入的空白作為分隔符或者結束符。

next()不能得到帶有空格的字元串

nextLine()特點:

1、以Enter為結束符,也就是說nextLine()方法傳回的是輸入回車之前的所有字元。

2、可以獲得空白.

例如:

public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);        
        //next方式接收字元串
        System.out.println("next方式接收:");
        String nextStr = sc.next();
        String nextStr2 = sc.next();
        System.out.println("next()輸入結果:\n"+nextStr+nextStr2);
        //nextLine方式接收字元串
        System.out.println("nextLine方式接收:");
        String nextLineStr = sc.nextLine();
        System.out.println("第二個nextLine:");
        String nextLineStr2 = sc.nextLine();
        System.out.println("nextLine()輸入結果:"+nextLineStr+"\n"+nextLineStr2);
        sc.close();
    }
           

運作結果:

next方式接收:

i’m haydn

next()輸入結果:

i’mhaydn

nextLine方式接收:

第二個nextLine:

i’m haydn

nextLine()輸入結果:

i’m haydn

總結:雖然這裡隻列出了控制台輸入的這一種方法,但是其他方式獲得的結果和結論是一緻的。掌握兩者之間的差別,以便更好的利用這兩個方法。