- 废话少说,如果你想获取包含空格的字符串,就用nextLine()
- next()是获取不到空格的。next()对于空格,作废处理。
import java.util.Scanner;
public class Main
{
public static void main(String [] args)
{
Scanner sc=new Scanner(System.in);
String str=sc.next();
System.out.println(str);
System.out.println("字符串的长度是:"+str.length());
}
}
对于上面的代码,如果输入“二”,然后输入几个空格,再输入“哈”,按下回车,控制台只打印“二”,“哈”没了。
3. 总而言之,想要获取到空格,就要用nextLine()方法,因为next()获取不到空格。