Java sanner類中next和nextLine的區別

來源:互聯網
上載者:User

標籤:san   讀取   字串   最好   結束   xxx   分隔字元   ati   lib   

next() 與 nextLine() 區別next():

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

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

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

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

nextLine():

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

2、可以獲得空白。

範例程式碼:

import java.util.Scanner;

public class ScannerText {

 

public static void main(String[] args) {

    Scanner scan=new Scanner(System.in);//從鍵盤接收資料

    int i=0;//定義一個整型變數

    float f=0.0f;//定義一個浮點型變數

    System.out.println("輸入整數:");

    if(scan.hasNextInt()){  //判斷輸入的是否是整數       

    i=scan.nextInt();//接收整數   

    System.out.println("整數資料:"+i);

    }

    else{

     //輸入錯誤的資訊

     System.out.println("輸入的不是整數!");

    

    }

    //輸入小數

    System.out.println("輸入小數:");

    if(scan.hasNextFloat()){//判斷輸入的是否是小數

     f=scan.nextFloat();//接收小數

     System.out.println("小數資料是:"+f);

    }

    else{

     System.out.println("輸入的不是小數!");

    }

}

 

}

 

如果要輸入 int 或 float 類型的資料,在 Scanner 類中也有支援,但是在輸入之前最好先使用 hasNextXxx() 方法進行驗證,再使用 nextXxx() 來讀取,和以上兩個差不多

Java sanner類中next和nextLine的區別

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.