Scanner

Scanner对象

获取用户的输入

基本语法

Scanner s =new Scanner(System.in);


通过Scanner类的next()与nextLine()方法获取输入的字符串,在读取前我们一般需要使用hasNext()与hasNextLine()判断是否还有输入的数据。


输入new Scanner(System.in);后 ALT+Enter出现:

import java.util.Scanner;

next()

package 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);
        }
        scanner.close();
              //凡是属于I0流的类如果不关闭会一直占用资源,要养成良好习惯用完就关掉
    }
}

输入Hello world,输出Hello,因为next只能接收到第一个有效字符到空格之间的字符,所有输入Hello world后只会接收“Hello”而接收不到“空格world”


nextLine

import java.util.Scanner;

public class Demo01 {
    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();
    }
}


去掉if判断

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();
    }
}

可以去掉if判断,结果一样

posted @ 2021-04-06 20:37  HT625  阅读(45)  评论(0)    收藏  举报