Java中获取用户输入的字符串,何时使用next()和nextLine()

  1. 废话少说,如果你想获取包含空格的字符串,就用nextLine()
  2. 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()获取不到空格。

发布了33 篇原创文章 · 获赞 0 · 访问量 1424

猜你喜欢

转载自blog.csdn.net/Deep_rooted/article/details/104283581