用户交互Scanner


用户交互Scanner

 

next()

Scanner scanner = new Scanner(System.in); //创建一个扫描器对象,用于接收键盘数据。
?
System.out.println("使用next方式接收:");
?
if(scanner.hasNext()){   //判断用户有没有输入字符串
   String str = scanner.next();   //使用next方式接收输入的字符串
   System.out.println("输入的内容为:"+str);
}
?
scanner.close(); //凡是属于IO(输入输出)流的类如果不关闭会一直占用资源,要养成习惯用完就关掉。

使用next方式接收: hello world 输入的内容为:hello

  • next()在读到第一个有效字符后,遇到空白就会停止,此处的空白包括空格和回车,作为结束符。

  • 在没有输入任何字符之前遇到的空白是无所谓的。

  • 也就是说next()不能得到带有空格的字符串。

 


 

nextLine()

Scanner scanner = new Scanner(System.in);
?
System.out.println("使用nextLine方式接收:");
?
if(scanner.hasNext()){
   String str = scanner.nextLine();
   System.out.println("输出的内容为:"+str);
}
scanner.close();

使用nextLine方式接收: hello world 输出的内容为:hello world

  • nextLine()方法只以回车为结束符,可以获得带有空格的字符串。

相关