javaのnextInt()、next()とnext Line()


ブログからの投稿:http://www.cnblogs.com/Skyar/p/5892825.html
説明:
nextInt():it only reads the int value、 nextInt()places the cursor in the same line after reading the input.
next(): read the input only till the space.It can't read t words separated by space.Also,next()place the cursor in the same line after reading the input.
nextLine():  reads input including space between the wods.OnextLink()positions the end of line.Onece the input is read,nextline()positions the cursor in the next line.
nextInt()、next()とnextLine()の違いはもうはっきりしました.一番間違えやすいのはcursorの問題だと思います.
次のコードを見てください
 1 import java.util.Scanner;
 2 
 3 public class MaxMap {
 4     public static void main(String[] args){
 5         Scanner cin = new Scanner(System.in);
 6         int n = cin.nextInt();
 7         String str = cin.nextLine();
 8         System.out.println("END");
 9         }
10 }            

実行後の結果:

実行結果から見て、String str=cin.nextLine()を直接スキップしたようです.この行のコードです
そうではないです.nextInt()は数値だけを読み取って、残りはまだ読み終わっていないので、cursorを本行に置いています.nextLine()は「」を読み出して終了します. reads till the end of line)
nextInt()の後で1行を読み取るには、nextInt()の後にcin.nextLine()を追加します.コードは以下の通りです.
import java.util.Scanner;

public class MaxMap {
    public static void main(String[] args){
        Scanner cin = new Scanner(System.in);
        int n = cin.nextInt();
        cin.nextLine();
        String str = cin.nextLine();
        System.out.println("END");
        }
}

下記のコードを見ています.
 1 import java.util.Scanner;
 2 
 3 public class MaxMap {
 4     public static void main(String[] args){
 5         Scanner cin = new Scanner(System.in);
 6         String n = cin.next();
 7         //cin.nextLine();
 8         String str = cin.nextLine();
 9         System.out.println("END");
10         System.out.println("next()read:"+n);
11         System.out.println("nextLine()read:"+str);
12     }
13 }

実行結果:


 理由:next()はスペースの前のデータを読み、また、cursorは本行を指し、後のnextLine()は前の残したデータを引き続き読みます.
ライン全体を読みたいなら、nextLine()を使います.
読み出し数字はnextLine()も使用できますが、変換が必要です.Integer.parseInt(cin.nextLine().
注意next()、nextInt()とnextLine()が一緒に使用すると、next()、nextInt()が一部のデータを読み出すことがあります.