Java中next()和hasNext() ? nextLine()和hasNextLine()?區別詳解


java.util.Scanner 是 Java5 的新特征,可以通過 Scanner 類來獲取用戶的輸入。

Scanner sc = new Scanner(System.in);

通過 Scanner 類的 next() 與 nextLine() 方法獲取輸入的字符串,在讀取前我們一般需要 使用 hasNext 與 hasNextLine 判斷是否還有輸入的數據

首先看看next方法:

import java.util.Scanner;  
public class ScannerDemo {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        // 從鍵盤接收數據
        // next方式接收字符串
        System.out.println("next方式接收:");
        // 判斷是否還有輸入
        if (sc.hasNext()) {
            String str1 = sc.next();
            System.out.println("輸入的數據為:" + str1);
        }
        sc.close();
    }
}

輸出:

nextLine()方法:

import java.util.Scanner;
public class ScannerDemo {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        // 從鍵盤接收數據
        // nextLine方式接收字符串
        System.out.println("nextLine方式接收:");
        // 判斷是否還有輸入
        if (sc.hasNextLine()) {
            String str2 = sc.nextLine();
            System.out.println("輸入的數據為:" + str2);
        }
        sc.close();
    }
}

輸出:

next()與nextLine()比較:

next():

1、一定要讀取到有效字符后才可以結束輸入。
2、對輸入有效字符之前遇到的空白,next() 方法會自動將其去掉。
3、只有輸入有效字符后才將其后面輸入的空白作為分隔符或者結束符。
4、next() 不能得到帶有空格的字符串。
nextLine():

1、以Enter為結束符,也就是說 nextLine()方法返回的是輸入回車之前的所有字符
2、可以獲得空白。

參考原文:https://blog.csdn.net/Fly_as_tadpole/article/details/84203209


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM