📜  Javanext() 和 nextLine() 方法的区别

📅  最后修改于: 2021-09-12 11:14:51             🧑  作者: Mango

Java.util 包中的 Scanner 类,用于获取原始类型(如 int、double 等)和字符串。这是在Java程序中读取输入的最简单方法,但如果您想要一种输入法用于时间受限的场景(例如竞争性编程),则效率不高。扫描器类包含next()nextLine()方法。

在本文中,将讨论这两种方法之间的区别。

next() 方法: Java的next()方法存在于 Scanner 类中,用于获取用户的输入。为了使用这个方法,需要创建一个 Scanner 对象。此方法只能读取输入,直到遇到空格(“”)。换句话说,它从扫描器中找到并返回下一个完整的标记。

以下是如何在Java实现 next() 方法的示例:

Java
// Java program to demonstrate
// the next() method
  
import java.util.Scanner;
  
class GFG {
    public static void main(String[] args)
    {
        // Creating the Scanner object
        Scanner sc = new Scanner(System.in);
  
        // Use of the next() method
        String Inpt = sc.next();
        System.out.println(Inpt);
    }
}


Java
// Java program to demonstrate
// the nextLine() method
  
import java.util.Scanner;
  
class GFG {
    public static void main(String[] args)
    {
        // Creating the object of the
        // Scanner class
        Scanner sc = new Scanner(System.in);
  
        // Use of nextLine() method
        String Inpt = sc.nextLine();
        System.out.println(Inpt);
    }
}


输入:

Geeks for  
geeks

输出:

Geeks

nextLine() 方法: Java的nextLine()方法存在于 Scanner 类中,用于获取用户的输入。为了使用这个方法,需要创建一个 Scanner 对象。此方法可以读取输入直到行尾。换句话说,它可以接受输入直到换行或换行并结束获取’\n’或回车的输入。

以下是如何在Java实现 nextLine() 方法的示例:

Java

// Java program to demonstrate
// the nextLine() method
  
import java.util.Scanner;
  
class GFG {
    public static void main(String[] args)
    {
        // Creating the object of the
        // Scanner class
        Scanner sc = new Scanner(System.in);
  
        // Use of nextLine() method
        String Inpt = sc.nextLine();
        System.out.println(Inpt);
    }
}

输入:

Geeks for  
geeks

输出:

Geeks for 

下表描述了 next() 和 nextLine() 方法之间的区别:

Next() NextLine()
It read input from the input device till the space character. It read input from the input device till the line change.
It cannot read those words having space in it. It can read those words having space in it.
It ends reading the input after getting space. It ends reading the input after getting ‘\n’ or press enter.
It places the cursor in the same line after reading the input. It places the cursor in the next line after reading the input.
The escaping sequence of next() is space. The escaping sequence of nextLine() is ‘\n’.
Syntax to scan input:
Scanner.next()
Syntax to scan input:
Scanner.nextLine()