java输入Scanner

Scanner类用于获取用户输入

Scanner scan = new Scanner(System.in)

用法

读取之前用hasNext、hasNextLine判断是否有输入的数据

输入字符串

  1. next读入方法

    import java.util.Scanner;
    
    class ScannerDemo {
        public static void main(String[] args) {
            Scanner scan = new Scanner(System.in);
            
            System.out.println("next方式接受字符串:");
            if (scan.hasNext()) {
                String st1 = scan.next();					#读入
                System.out.println("输入的数据:" + st1);
            }
        }
    }
    

    next方式接受字符串:
    hello world
    输入的数据:hello

    • 自动去除有效字符之前的空格

    • 以空格作为结束符

  2. nextLine读入方法

    import java.util.Scanner;
    
    class ScannerDemo {
        public static void main(String[] args) {
            Scanner scan = new Scanner(System.in);
            
            System.out.println("nextLine方式接受字符串:");
            if (scan.hasNext()) {
                String str2 = scan.nextLine();				#读入
                System.out.println("输入的数据:" + str2);
            }
        }
    }
    

    nextLine方式接受字符串:
    hello world
    输入的数据:hello world

    • 以回车为结束符

输入数值

读取之前通过hasNextxxx()进行验证,使用nextxxx进行读取

  1. 以输入int型数据为例

    import java.util.Scanner;
    
    class ScannerDemo {
        public static void main(String[] args) {
            Scanner scan = new Scanner(System.in);
    
            int i = 0;
            System.out.println("输入整数:");
            if (scan.hasNextInt()) {					#判断是否为整型
                i = scan.nextInt();						#读入整型
                System.out.println("输入的整数:" + i);
            } else {
                System.out.println("输入的不是整数!");
            }
        }
    }
    

    输入整数:
    666
    输入的整数:666

    • 其他类型:float、Long等类似
  2. 换行输入多个数值

    import java.util.Scanner;
    
    class ScannerDemo {
        public static void main(String[] args) {
            Scanner scan = new Scanner(System.in);
            double sum = 0;
    
            while (scan.hasNextInt()) {			
                sum += scan.nextInt();
            }
            System.out.println("输入数值的总和:" + sum);
        }
    }
    

    1
    2
    3
    0.0
    输入数值的总和:6.0

    • 输入非特定类型值时结束
    • while循环输入
  3. 空格输入多个数值(一行)

    class ScannerDemo {
        public static void main(String[] args) {
            Scanner scan = new Scanner(System.in);
            List<Integer> a = new ArrayList();
    
            for (int i = 0; i < 5; i++) {
                a.add(scan.nextInt());
            }
            for (int i = 0; i < a.size(); i++) {
                System.out.println(a.get(i));
            }
        }
    }
    

    1 2 3 4 5
    1
    2
    3
    4
    5

    • nextInt:是读取下一个int,不管分隔符是空格还是回车
    • 或者是以字符串的形式用nextLine读入,用split分割,然后转换成int
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值