当前位置: 代码迷 >> 综合 >> Scanner类的next、nextLine、hasNext、hasNextLine
  详细解决方案

Scanner类的next、nextLine、hasNext、hasNextLine

热度:6   发布时间:2024-01-10 06:19:17.0
  • hasNext() 是检测还有没有下一个输入;
  • next() 是指针移动到当前下标,并取出下一个输入;
  • nextLine() 把指针移动到下一行 让然后取出当前这一行的输入;
  • hasNextLine() 是检测下一行有没有输入。
next/next**:

next 方法在缓存区读取内容时,会过滤掉有效字符前面的无效字符,对输入有效字符之前遇到的空格键Tab键Enter键等结束符,next 方法会自动将其过滤掉;只有在读取到有效字符之后,next 方法才将其后的空格键Tab键Enter键等视为结束符;所以next 方法不能得到带空格的字符串。

nextLine:

nextLine 方法字面上有扫描一整行的意思,它不会过滤掉无效字符,它的结束符只能是Enter键即换行键,即nextLine 方法返回的是换行之前没有被读取的所有字符,它是可以得到带空格的字符串的。

next 和 nextLine 连用

因为 next 方法只扫描到有效字符到结束符为止,而 nextLine 不会过滤无效字符,所以如果这时像下面 testNextLine() 里那样用,nextLine 会读取最后一个换行符,然后程序结束。

import java.util.Scanner;
/** * Windows环境 */
public class ScannerDemo {
    public static void main(String[] args){
    
// testNext();testNextLine();}private static void testNext() {
    Scanner reader = new Scanner(System.in);System.out.println("Please enter your age: ");int age = reader.nextInt(); // 20+"\r\n"System.out.println("Please enter your name: ");String name = reader.next(); // zhangsan+"\r\n"System.out.println("name=" + name);System.out.println("age=" + age);}private static void testNextLine() {
    Scanner reader = new Scanner(System.in);System.out.println("Please enter your age: ");int age = reader.nextInt();    // 20+"\r\n"System.out.println("Please enter your name: ");String name = reader.nextLine(); // 这里程序会直接结束,因为不会过滤结束符,读到 "\r" 直接结束System.out.println("name=" + name);System.out.println("age=" + age);}
}
hasNext 和 hasNextLine

当执行到 hasNext() 时,它会先扫描缓冲区中是否有字符,有则返回 true,继续扫描。直到扫描为空,这时并不返回 false,而是将方法阻塞,等待你输入内容然后继续扫描。

换而言之,使用了 hasNext() 方法程序永远不会结束,我们如果想达到没有输入程序停止的效果,需要使用带正则表达式参数的 hasNext(Pattern pattern) or hasNext(String pattern);hasNextLine() 与 hasNext() 用法类似,也是阻塞式的判断,而且 hasNextLine 并没有正则表达式参数的形式,所以一般只能用于文件的读取。

import java.util.Scanner;public class ScannerDemo {
    public static void main(String[] args){
    
// testHasNext();testHasNextLine();}private static void testHasNextLine() {
    System.out.println("Please enter a few lines: ");Scanner sc = new Scanner(System.in);while(sc.hasNextLine()) {
    System.out.println("The keyboard input is: " + sc.nextLine());}System.out.println("It will never be implemented here if use hasNextLine()");}private static void testHasNext() {
    System.out.println("Please enter a number of words separated by Spaces: ");Scanner sc = new Scanner(System.in);while(!sc.hasNext("#")) {
    System.out.println("The keyboard input is: " + sc.next());}System.out.println("It will never be implemented here if use hasNext()");}
}
  相关解决方案