用户交互Scanner

用户交互Scanner

package com.lzoro.scanner;

import java.util.Scanner;

public class Demo01 {
    public static void main(String[] args) {

        //创建一个扫描器对象,用于接收键盘数据
        Scanner scanner = new Scanner(System.in);

        System.out.println("使用next方式接收:");

        //判断用户有没有输入字符串
        if (scanner.hasNext()){
            //使用next方式接收
            String str = scanner.next();//程序会等待用户收入完毕
            System.out.println("输出的内容为:"+str);
        }

        //凡是属于IO流的类如果不关闭会一直占用资源,要养成良好的习惯,用完就关掉
        scanner.close();
    }
}

package com.lzoro.scanner;

import java.util.Scanner;

public class Demo02 {
    public static void main(String[] args) {
        //从键盘接收数据
        Scanner scanner = new Scanner(System.in);

        System.out.println("使用nextLine方式接收:");

        //判断是否还有输入
        if(scanner.hasNextLine()){

            String str = scanner.nextLine();
            System.out.println("输出内容为:"+str);
        }

        scanner.close();

    }
}

用户交互Scanner
package com.lzoro.scanner;

import java.util.Scanner;

public class Demo03 {
    public static void main(String[] args) {
        //从键盘接收数据
        Scanner scanner = new Scanner(System.in);

        System.out.println("请输入数据:");

        String str = scanner.nextLine();

        System.out.println("输出的内容为:"+str);

        scanner.close();
    }
}

package com.lzoro.scanner;

import java.sql.SQLOutput;
import java.util.Scanner;

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

        //从键盘接收数据
        int i = 0;
        float f = 0.0f;

        System.out.println("请输入整数:");

        //如果...那么
        if (scanner.hasNextInt()){
            i=scanner.nextInt();
            System.out.println("整数数据:"+i);
        }else {
            System.out.println("输入不是整数数据!");
        }

        System.out.println("请输入小数:");

        //如果...那么
        if (scanner.hasNextFloat()){
            f = scanner.nextFloat();
            System.out.println("小数数据:"+f);
        }else{
            System.out.println("输入的不是小数数据!");
        }

        scanner.close();

    }
}

package com.lzoro.scanner;

import java.util.Scanner;

public class Demo05 {
    public static void main(String[] args) {
        //可以输入多个数字,并求其总和与平均数,每输入一个数用回车确定,通过输入非数字来结束输入并输出执行结果:
        Scanner scanner = new Scanner(System.in);
        int m = 0;
        double sum = 0;

        while (scanner.hasNextDouble()){
            double x = scanner.nextDouble();
            m = m+1;//m++
            sum = sum + x;
            System.out.println("你输入了第"+m+"个数据,当前结果为sum="+sum);
        }
        System.out.println(m +"个数的和为"+ sum);
        System.out.println(m +"个数的平均值是"+ (sum/m));

        scanner.close();
    }
}

用户交互Scanner

上一篇:项目端口被占用,报错Error: listen EADDRINUSE: address already in use 127.0.0.1:8080,npm ERR! lshan@1.0.0 dev:


下一篇:compileSdkVersion minSdkVersion targetSdkVersion