前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >Java中Scanner用法总结

Java中Scanner用法总结

作者头像
全栈程序员站长
发布2022-09-09 09:38:07
发布2022-09-09 09:38:07
59400
代码可运行
举报
运行总次数:0
代码可运行

大家好,又见面了,我是你们的朋友全栈君。

最近在做OJ类问题的时候,经常由于Scanner的使用造成一些细节问题导致程序不通过(最惨的就是网易笔试,由于sc死循环了也没发现,导致AC代码也不能通过。。。),因此对Scanner进行了一些总结整理。(我的github:https://github.com/MonkeyJJC?tab=repositories)

Scanner类简介

Java 5添加了java.util.Scanner类,这是一个用于扫描输入文本的新的实用程序。它是以前的StringTokenizer和Matcher类之间的某种结合。由于任何数据都必须通过同一模式的捕获组检索或通过使用一个索引来检索文本的各个部分。于是可以结合使用正则表达式和从输入流中检索特定类型数据项的方法。这样,除了能使用正则表达式之外,Scanner类还可以任意地对字符串和基本类型(如int和double)的数据进行分析。借助于Scanner,可以针对任何要处理的文本内容编写自定义的语法分析器。

关于nextInt()、next()和nextLine()的理解

nextInt(): it only reads the int value, nextInt() places the cursor(光标) in the same line after reading the input.(nextInt()只读取数值,剩下”\n”还没有读取,并将cursor放在本行中)

next(): read the input only till the space. It can’t read two words separated by space. Also, next() places the cursor in the same line after reading the input.(next()只读空格之前的数据,并且cursor指向本行) next() 方法遇见第一个有效字符(非空格,非换行符)时,开始扫描,当遇见第一个分隔符或结束符(空格或换行符)时,结束扫描,获取扫描到的内容,即获得第一个扫描到的不含空格、换行符的单个字符串。

nextLine(): reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line. nextLine()时,则可以扫描到一行内容并作为一个字符串而被获取到。

代码语言:javascript
代码运行次数:0
运行
复制
public class NextTest{  
    public static void main(String[] args) {  
        String s1,s2;  
        Scanner sc=new Scanner(System.in);  
        System.out.print("请输入第一个字符串:");  
        s1=sc.nextLine();  
        System.out.print("请输入第二个字符串:");  
        s2=sc.next();  
        System.out.println("输入的字符串是:"+s1+" "+s2);  
    }  
}  

结果:

代码语言:javascript
代码运行次数:0
运行
复制
请输入第一个字符串:home
请输入第二个字符串:work
输入的字符串是:home work

把上面的程序修改一下:

代码语言:javascript
代码运行次数:0
运行
复制
s1=sc.next();  
s2=sc.nextLine();  

运行结果:

代码语言:javascript
代码运行次数:0
运行
复制
请输入第一个字符串:home
请输入第二个字符串:输入的字符串是:home

可以看到,nextLine()自动读取了被next()去掉的Enter作为他的结束符,所以没办法给s2从键盘输入值。经过验证,我发现其他的next的方法,如double nextDouble() , float nextFloat() , int nextInt() 等与nextLine()连用时都存在这个问题,解决的办法是:在每一个 next()、nextDouble() 、 nextFloat()、nextInt() 等语句之后加一个nextLine()语句,将被next()去掉的Enter结束符过滤掉

代码语言:javascript
代码运行次数:0
运行
复制
public class NextTest{  
    public static void main(String[] args) {  
        String s1,s2;  
        Scanner sc=new Scanner(System.in);  
        System.out.print("请输入第一个字符串:");  
        s1=sc.next();  
        sc.nextLine();
        System.out.print("请输入第二个字符串:");  
        s2=sc.nextLine();  
        System.out.println("输入的字符串是:"+s1+" "+s2);  
    }  
}  

运行结果:

代码语言:javascript
代码运行次数:0
运行
复制
请输入第一个字符串:home
请输入第二个字符串:work
输入的字符串是:home work

循环输入多组测试用例

一个while就是一个测试用例

代码语言:javascript
代码运行次数:0
运行
复制
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);

        // 一个while就是一个测试用例
        while(in.hasNext()){
            int n = in.nextInt(); // 该测试用例后续接收的参数个数
            long[] array = new long[n];
            String[] arrayStr = new String[n];
            for(int i=0; i<n; i++){
                arrayStr[i] = in.next();
            }
            for(int i=0; i<n; i++){
                array[i] = in.nextLong();// 取下一个元素转换成long类型
            }

            System.out.println(Arrays.toString(array)+" "+ Arrays.toString(arrayStr));
        }
    }

一个与容器结合的综合例子:

代码语言:javascript
代码运行次数:0
运行
复制
import java.util.Scanner;    
public class Main {    
    public static void main(String[] args) {    
        Scanner in = new Scanner(System.in);    
        while (in.hasNext()) {    
            int n = in.nextInt();   
        /* nextLine()是扫描器执行当前行,并返回跳过的输入信息,特别需要注意!!! 
 
            如果没有该行,则执行第一个in.nextLine()命令时的返回值是int n = in.nextInt()的值*/   
            in.nextLine();  
        HashSet<String> set = new HashSet<String>();  
        for (int i = 0; i < n; i++) {   
        String line =   
  
        in.nextLine();   
        String[] arr = line.split(" ");   
        for (int j = 0; j < arr.length; j++) {   
            set.add(arr[j]);   
        }  
         }  
        System.out.println("sum:" + set.size());    
    
    }    
}  

输入: 3 a b c d e f a b c 输出: 6

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/162041.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Scanner类简介
  • 关于nextInt()、next()和nextLine()的理解
  • 循环输入多组测试用例
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档