zoukankan      html  css  js  c++  java
  • Java中的Scanner类学习

    转载自:

    Java中Scanner的nextInt(),next(),nextLine()方法总结

    今天在java上机课时遇到了个小问题,使用Scanner输入数据时,使用了一次nextInt(),一次nextLine(),却只接收了一个整数。代码如下

    code1:

          

    复制代码
     1 package cn.dx;
     2 
     3 import java.util.Scanner;
     4 
     5 public class ScannerTest {
     6 
     7     public static void main(String[] args) {
     8         Scanner in =  new Scanner(System.in);
     9         System.out.println("请输入一个整数");
    10         while(in.hasNextInt()){
    11             int num = in.nextInt();
    12             System.out.println("请输入一个字符串");
    13             String str = in.nextLine();
    14             System.out.println("num="+num+",str="+str);
    15             System.out.println("请输入一个整数");
    16         }
    17     }
    18 }
    复制代码

    运行结果为:

         请输入一个整数
         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类型的变量。

          之后改用了next()方法

          code2.

         

    复制代码
     1 package cn.dx;
     2 
     3 import java.util.Scanner;
     4 
     5 public class ScannerTest {
     6 
     7     public static void main(String[] args) {
     8         Scanner in =  new Scanner(System.in);
     9         System.out.println("请输入一个整数");
    10         while(in.hasNextInt()){
    11             int num = in.nextInt();
    12             System.out.println("请输入一个字符串");
    13             String str = in.next();
    14             System.out.println("num="+num+",str="+str);
    15             System.out.println("请输入一个整数");
    16         }
    17     }
    18 }
    复制代码

             运行后结果是正确的,运行结果如下。

            请输入一个整数
            123
            请输入一个字符串
            sdjakl
            num=123,str=sdjakl
            

            请输入一个整数
            213 jdskals
            请输入一个字符串
            num=213,str=jdskals
            请输入一个整数  

     试验后发现next()方法是以换行或者空格符为分界线接收下一个String类型变量。

    useDelimiter(String regex)方法的使用

  • 相关阅读:
    BroadcastReceiver 小结
    Android Manifest.xml 之 Intent-filter
    First Phone Interview
    XDK html development --- Cross Domain Request
    Github Git usage
    为节省内存,动态添加view布局和控件
    相似的概念
    让一个view 获得焦点
    ListView 关于减少耗时方法调用优化
    SearchView 分解设置属性
  • 原文地址:https://www.cnblogs.com/njupt-Qsimple/p/5481342.html
Copyright © 2011-2022 走看看