用户交互Scanner

用户交互Scanner

package com.beijing.xiaowen.scanner;

import java.util.Scanner;

public class Demo01 {
    public static void main(String[] args) {
        //接受键盘输入内容
        Scanner scanner = new Scanner(System.in);
        System.out.println("输入内容:");

        //判断是否还有输入
        if (scanner.hasNextLine()){
            String next = scanner.nextLine();
            System.out.println(next);
        }
/*
        //.next() 不能接收带有空的字符串 如 输入hello world
        //         则只输出 hello
        if (scanner.hasNext()){
            String next = scanner.next();
            System.out.println(next);
        }
*/

        //关闭资源
        scanner.close();
    }
}

package com.beijing.xiaowen.scanner;

import java.util.Scanner;

public class Demo02 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        double sum = 0;
        int a = 0;

        while (scanner.hasNextDouble()){
            double x = scanner.nextDouble();
            a++;
            sum = sum + x;
            System.out.println("输入:"+a+"个数"+",和为:"+sum);
        }
        scanner.close();
    }
}

posted @ 2022-10-19 23:10  Always_0708  阅读(18)  评论(0)    收藏  举报