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.

猜你喜欢

转载自blog.csdn.net/u014158743/article/details/52579215