Java中next()、nextLine()、以及nextInt()的區別及用法

Java中的Scanner包中的next()、nextLine()、nextInt()都是用來讀取輸入的方法,但它們之間存在一點細微的區別,這裏我們一一舉例說明:

首先總結一下:主要區別在於對空格的處理方式不同。

next()方法:

import java.util.Scanner;
public class test {
    public static void main(String args[]){
        Scanner sc=new Scanner(System.in);
        System.out.println("使用next()方法,輸入爲:");
        while(sc.hasNext()){
           String val=sc.next();
           System.out.println("輸出爲:");
           System.out.println(val);
        }
    }

}

運行結果:

從上可知:使用next()方法讀取輸入時是將空格作爲兩個字符串之間的間隔來處理。

 

nextLine()方法:

import java.util.Scanner;
public class test {
    public static void main(String args[]){
        Scanner sc=new Scanner(System.in);
        System.out.println("使用nextLine()方法,輸入爲:");
        String val=sc.nextLine();
        System.out.println("輸出爲:");
        System.out.println(val);
    }

}

運行結果:

從上可知:使用nextLine()方法讀取輸入時是將空格作爲整個輸入字符串的一部分。

 

nextInt()方法:

import java.util.Scanner;
public class test {
    public static void main(String args[]){
        Scanner sc=new Scanner(System.in);
        System.out.println("使用nextInt()方法,輸入爲:");
        while(sc.hasNext()){
            int val=sc.nextInt();
            System.out.println("輸出爲:");
            System.out.println(val);
        }
    }

}

運行結果:

此時需注意,若輸入不是int類型,則會報錯:

從上可知:

使用nextInt()方法時,處理空格的方式與next()類似,將空格作爲兩個輸入數據之間的間隔,只是它的返回值是int類型。

並且當使用nexInt()方法時,只能輸入int類型的數據。

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章