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)方法的使用

  • 相关阅读:
    Docker决战到底(三) Rancher2.x的安装与使用
    golang实现给图片加水印
    golang实现图片水印效果
    百度ueditor 编辑器使用问题收集
    重要的文件和数据,别放在/tmp下
    在CentOS 7上切换默认的java版本
    [转载]Centos和RedHat的区别和联系
    在Excel的公式框内输入换行符
    Outlook打不开,报错信息为“The time limit for logging on was reached while waiting for system resources. Try again. MAPI 1.0 [000004C2]”
    VMXNET3与E1000E与E1000的比较
  • 原文地址:https://www.cnblogs.com/njupt-Qsimple/p/5481342.html
Copyright © 2011-2022 走看看