• 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
  • 相关阅读:
    Cpp知识点系列-宏定义
    java计算机毕业设计客服管理系统源码+mysql数据库+系统+lw文档+部署
    学习太极创客 — MQTT(八)ESP8266订阅MQTT主题
    线上展厅视觉奇观 广州商迪
    AR Engine光照估计能力,让虚拟物体在现实世界更具真实感
    预约按摩小程序功能及使用指南;
    【Dubbo】Dubbo负载均衡实现解析
    基于 Transformer 的中文对联生成器
    深度学习在自然语言处理中的应用
    SpringBoot 常用注解的原理和使用
  • 原文地址:https://blog.csdn.net/weixin_41072572/article/details/126185801