• Scanner之nextInt()方法的使用


    @TOC

    package com;
    
    import java.util.Scanner;
    
    public class text3 {
        public static void main(String[] args) {
            Scanner in=new Scanner(System.in);
            int len=in.nextInt();
            System.out.println("len:"+len);
            int[] nums=new int[len];
            int i=0;
            while(in.hasNextInt()){
                int a=in.nextInt();
                nums[i]=a;
                i++;
                if(i>=len){
                    break;
                }
            }
            int k=in.nextInt();
            for(int j=0;j
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

    nextInt()方法接收一个整形数据,该方法以空白符或者换行符作为分隔符读取输入中的下一个整形数据,中间的多个空格符或者换行符都被跳过,读取完之后,光标依然停留在当前行。如需要让光标读取下一行的数据,则需要用nextLine()方法读取缓存中的换行符之后移动到下一行。

    hasNext表示输入中是否还有数据,有则返回true,否则返回false,代码示例如下。

    package com;
    
    import java.util.Scanner;
    
    public class text3 {
        public static void main(String[] args) {
            Scanner in=new Scanner(System.in);
            while(in.hasNext()){
                int a=in.nextInt();
                double b=in.nextDouble();
                String s=in.nextLine();
                System.out.println(a+s+b);
            }
        }
    }
    
    输入:1 3.3 asd
    输出:1 asd3.3
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    hasNextInt()则表示输入中是否还有整形数据,有则返回true,否则返回false。

    
    
    • 1

    public class text3 {
    public static void main(String[] args) {
    Scanner in=new Scanner(System.in);
    while(in.hasNextInt()){
    int a=in.nextInt();
    System.out.println(a);
    }
    }
    }

    输入:1 as d
    输出:1

    输入:1 as 3
    输出:1

    
    
    • 1
  • 相关阅读:
    布隆过滤器
    java处理时间-去除节假日以及双休日
    Ruo-Yi前后端分离相关笔记
    力扣第108题 将有序数组转二叉搜索树 c++
    什么是单元测试(unit testing)
    Springboot2.0踩得坑(embeddedservletcontainercustomizer)
    自行车轴承市场调研:预计2028年将达到25.6亿美元
    764、最大加号标志
    【Hadoop】HDFS API 操作大全
    MySQL - 深入理解锁机制和实战场景
  • 原文地址:https://blog.csdn.net/weixin_41072572/article/details/126185801