About Scanner
This article introduced the Scanner class.
Iβm back to Java, a language for object-oriented coding, this time to prepare for a coding test and make it relevant to my job. I wanted to write a post about the scanner class that Iβve been working on.
What is a Scanner object?
To create an object, you can give the constructor a parameter value from System.in, as shown in the example below.
Example
Scanner scanner = new Scanner(System.in);
In the Scanner class, the next() and nextLine() methods return the value of the parameter as a String.
What is the difference between next() and nextLine() methods?
Example of the difference between next() and nextLine() methods
import java.util.Scanner;
public class scannerExample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// input: abcde fghij
String a = sc.next();
System.out.println(a);
// result: abcde
String b = sc.nextLine();
System.out.println(b);
// result: abcde fghij
}
}
Referring to the comments in the example, the difference between the nextLine() and next() methods is that the nextLine() method returns all of the string up to the newline, while the next() method returns the string as input up to the whitespace.
Conclusion
If you want to return a single line with spaces, use the nextLine() method, and if you want to return a single word, use the next() method.