Java中Scanner的nextInt(),next(),nextLine()方法總結

前言:借別人的例子做個總結。
原文出處:http://www.cnblogs.com/gold-worker/archive/2013/04/10/3013063.html

代碼一

 package cn.dx;
 import java.util.Scanner;
 public class ScannerTest {

     public static void main(String[] args) {
         Scanner in =  new Scanner(System.in);
         System.out.println("請輸入一個整數");
         while(in.hasNextInt()){
             int num = in.nextInt();
             System.out.println("請輸入一個字符串");
             String str = in.nextLine();
             System.out.println("num="+num+",str="+str);
             System.out.println("請輸入一個整數");
         }
     }
 }

結果一


請輸入一個整數
1231
請輸入一個字符串
num=1231,str=
請輸入一個整數

第二個String類型的參數沒有讀取進來。

自己查看了下nextInt()和nextLine()方法的官方文檔

  nextLine()

  Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line. 

  nextInt()方法會讀取下一個int型標誌的token.但是焦點不會移動到下一行,仍然處在這一行上。當使用nextLine()方法時會讀取改行剩餘的所有的內容,包括換行符,然後把焦點移動到下一行的開頭。所以這樣就無法接收到下一行輸入的String類型的變量。

代碼二

 package cn.dx; 
 import java.util.Scanner;
 public class ScannerTest {

     public static void main(String[] args) {
         Scanner in =  new Scanner(System.in);
         System.out.println("請輸入一個整數");
         while(in.hasNextInt()){
             int num = in.nextInt();
             System.out.println("請輸入一個字符串");
             String str = in.next();
             System.out.println("num="+num+",str="+str);
             System.out.println("請輸入一個整數");
         }
     }
 }

結果二

請輸入一個整數
123
請輸入一個字符串
sdjakl
num=123,str=sdjakl

請輸入一個整數
213 jdskals
請輸入一個字符串
num=213,str=jdskals
請輸入一個整數

總結:

Scanner(InputStream in)

constructs a Scanner object from the given input stream.

String nextLine()

reads the next line of input.

String next()

reads the next word of input (delimited by whitespace).

int nextInt()

double nextDouble()

read and convert the next character sequence that represents an
integer or floating-point number.

boolean hasNext()

tests whether there is another word in the input.

boolean hasNextInt()

boolean hasNextDouble()

test whether the next character sequence represents an integer or
floating-point number.

發佈了41 篇原創文章 · 獲贊 10 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章