next 与 nextline 方法使用介绍

next 方法使用介绍
import java.util.Scanner;

public class scanner {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("使用next方式接收:");
        //判断用户是否输出字符串
        if(scanner.hasNext()){
            //使用netx的方式接收
            String str = scanner.next();
            System.out.println("输出的内容为:" + str);
        }
        //只是是属于IO流的类如果不关闭会一直占用资源,所以要养成关闭的习惯
        scanner.close();
        //next方法 接收不了带有空格的字符串,会读取到有效字符后,将下一个空格作为结束符,结束读取
        //上述 if语句 可以不使用
    }
}
nextLine方法使用介绍
import java.util.Scanner;

public class scanner02 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        //使用nextLine方法接收
        System.out.println("使用nextLine方式接收:");

        if(scanner.hasNextLine()){
            //使用nextLine方式接收
            String str = scanner.nextLine();
            System.out.println("输出的内容为:" + str);
        }
        //只是是属于IO流的类如果不关闭会一直占用资源,所以要养成关闭的习惯
        scanner.close();
        //nextLine方法 可以接受空格,以 Enter 作为结束符
        //上述 if语句 可以不使用
    }
}
posted @ 2024-12-29 16:43  EndeavorX  阅读(57)  评论(0)    收藏  举报