• 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
  • 相关阅读:
    全球与中国吸油烟机行业市场规模调研及未来前瞻报告2022-2028年
    【书籍篇】Spring实战第4版 第2部分 Web中的Spring
    之前续写抖音开发者接入字节小游戏的缓存一下,现在说一下在 Windows 或者 Mac 如何用终端更换路径?
    CentOS同时安装mysql8.0
    day09-1存储引擎
    day065:IO流、字节流、字节流写数据
    怎么修复vcomp140.dll丢失问题?5个详细的修复方法分享
    教你用JavaScript实现随机点名
    投资理财:增额终身寿的优点和缺点
    for forin forof forEach map区别
  • 原文地址:https://blog.csdn.net/weixin_41072572/article/details/126185801