Scanner

键盘接收数据

//从键盘接收数据
Scanner scanner = new Scanner(System.in);
System.out.println("请输入:");
if (scanner.hasNext()==true){//判断是否输入有值 以回车为判断结束输出
    String str=scanner.nextLine();//把内容输出包括空格 而next内容输出不包括空格
    System.out.println("输出结果:"+str);
}
scanner.close
public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入:");
        int a=0;
        float b=0.0F;
        if (scanner.hasNextInt()){
            a=scanner.nextInt();
            System.out.println("您输入的整数为:"+a);
        }else if (scanner.hasNextFloat()) {
            b=scanner.nextFloat();
            System.out.println("您输入的小数为:"+b);
        }else  {
            System.out.println("您输入有误!!");
        }
    }

求和与平均值

public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        double sum=0;
        int num=0;
        while (scanner.hasNextDouble()){
            num++;
            sum=sum+scanner.nextDouble();
        }
        System.out.println("总和为:"+sum);
        System.out.println("平均值为:"+sum/num);
        scanner.close();
    }