next()和nextLine()区别

next()一定要读取到有效字符后才可以结束输入,对输入有效字符之前遇到的空格键、Tab键或Enter键等结束符,next()方法会自动将其去掉,只有在输入有效字符之后,next()方法才将其后输入的空格键、Tab键或Enter键等视为分隔符或结束符。
完整标记的前后是与分隔模式匹配的输入信息所以next()不能得到带空格的字符串,而nextLine()是遇到回车是才结束,所以可以得到带空格的字符串

package com.web;

import java.util.Scanner;

public class Test46 {
    
    
    public static void main(String[] args) {
    
    
        method1();
        method2();
    }
    //next()不读取空格
    private static void method1() {
    
    
        Scanner scanner1 = new Scanner(System.in);
        System.out.print("INPUT STRING 1 :");
        String str1 = scanner1.next();
        System.out.println(str1);//i

    }
    //nextLine()读取空格
    private static void method2() {
    
    
        Scanner scanner2 = new Scanner(System.in);
        System.out.print("INPUT STRING 2 :");
        String str2 = scanner2.nextLine();
        System.out.println(str2);//i love you
    }

}

Guess you like

Origin blog.csdn.net/djydjy3333/article/details/121519730