YouTip LogoYouTip

Java Scanner Class

java.util.Scanner is a new feature in Java 5. We can use the Scanner class to obtain user input. Below is the basic syntax for creating a Scanner object: Scanner s = new Scanner(System.in); Next, we demonstrate the simplest data input and use the Scanner class's `next()` and `nextLine()` methods to obtain the input string. Before reading, we generally need to use `hasNext` and `hasNextLine` to check if there is more input data: ### Using the next Method: ## ScannerDemo.java File Code: import java.util.Scanner; public class ScannerDemo{public static void main(String[]args){Scanner scan = new Scanner(System.in); System.out.println("nextReceiving method:"); if(scan.hasNext()){String str1 = scan.next(); System.out.println("Input data is:" + str1); }scan.close(); }} Executing the above program produces the following output: $ javac ScannerDemo.java $ java ScannerDemonextReceiving method: tutorial com Input data is: tutorial You can see that the string "com" was not output. Next, let's look at nextLine. ### Using the nextLine Method: ## ScannerDemo.java File Code: import java.util.Scanner; public class ScannerDemo{public static void main(String[]args){Scanner scan = new Scanner(System.in); System.out.println("nextLineReceiving method:"); if(scan.hasNextLine()){String str2 = scan.nextLine(); System.out.println("Input data is:" + str2); }scan.close(); }} Executing the above program produces the following output: $ javac ScannerDemo.java $ java ScannerDemo nextLineReceiving method: tutorial com Input data is: tutorial com You can see that the string "com" was output. ### Difference between next() and nextLine() next(): * 1. It must read valid characters before the input can end. * 2. It automatically discards any whitespace encountered before the valid characters. * 3. Only after reading valid characters does it treat subsequent whitespace as a delimiter or terminator. * 4. next() cannot obtain a string containing spaces. nextLine(): * 1. It uses Enter as the terminator, meaning the nextLine() method returns all characters entered before the carriage return. * 2. It can obtain whitespace. If you want to input data of type `int` or `float`, the Scanner class also supports this. However, it's best to use the `hasNextXxx()` method for validation before input, and then use `nextXxx()` to read: ## ScannerDemo.java File Code: import java.util.Scanner; public class ScannerDemo{public static void main(String[]args){Scanner scan = new Scanner(System.in); int i = 0; float f = 0.0 f; System.out.print("Enter integer:"); if(scan.hasNextInt()){i = scan.nextInt(); System.out.println("Integer data:" + i); }else{System.out.println("Input is not an integer!"); }System.out.print("Enter decimal:"); if(scan.hasNextFloat()){f = scan.nextFloat(); System.out.println("Decimal data:" + f); }else{System.out.println("Input is not a decimal!"); }scan.close(); }} Executing the above program produces the following output: $ javac ScannerDemo.java $ java ScannerDemoEnter integer: 12 Integer data: 12 Enter decimal: 1.2Decimal data: 1.2 In the following example, we can input multiple numbers, calculate their sum and average. Each number is confirmed by pressing Enter. Inputting a non-numeric value ends the input and outputs the result: ## ScannerDemo.java File Code: import java.util.Scanner; class TutorialTest{public static void main(String[]args){System.out.println("Please enter a number:"); Scanner scan = new Scanner(System.in); double sum = 0; int m = 0; while(scan.hasNextDouble()){double x = scan.nextDouble(); m = m + 1; sum = sum + x; }System.out.println(m + "The sum of the numbers is" + sum); System.out.println(m + "The average of the numbers is" + (sum / m)); scan.close(); }} Executing the above program produces the following output (input a non-numeric value to end the input): $ javac ScannerDemo.java $ java ScannerDemoPlease enter a number: 12231521.4end4The sum of the numbers is 71.44The average of the numbers is 17.85 * * * ## Common Methods | Method | Description | | --- | --- | | **Constructor Methods** | | `Scanner(File source)` | Creates a Scanner from a file | | `Scanner(InputStream source)` | Creates a Scanner from an input stream | | `Scanner(String source)` | Creates a Scanner from a string | | **Basic Input Methods** | | `boolean hasNext()` | Checks if there is another token (delimited by whitespace) | | `String next()` | Reads the next token (as a string) | | `boolean hasNextLine()` | Checks if there is another line | | `String nextLine()` | Reads the next line of content | | **Type Checking Methods** | | `boolean hasNextInt()` | Checks if the next token is an integer | | `boolean hasNextDouble()` | Checks if the next token is a double | | `boolean hasNextBoolean()` | Checks if the next token is a boolean | | **Type Reading Methods** | | `int nextInt()` | Reads the next integer | | `double nextDouble()` | Reads the next double | | `boolean nextBoolean()` | Reads the next boolean | | `long nextLong()` | Reads the next long integer | | `float nextFloat()` | Reads the next float | | `short nextShort()` | Reads the next short integer | | `byte nextByte()` | Reads the next byte | | **Delimiter Control** | | `Scanner useDelimiter(String pattern)` | Sets the delimiter pattern | | `Scanner useDelimiter(Pattern pattern)` | Sets the delimiter using a regular expression | | `String delimiter()` | Returns the current delimiter pattern | | **Other Methods** | | `void close()` | Closes the scanner | | `Scanner skip(Pattern pattern)` | Skips input matching the specified pattern | | `Scanner skip(String pattern)` | Skips input matching the specified string | | `String findInLine(Pattern pattern)` | Finds the specified pattern in the current line | | `String findInLine(String pattern)` | Finds the specified string in the current line | | `Scanner reset()` | Resets the scanner | | `Locale locale()` | Returns the locale currently used by this scanner | | `Scanner useLocale(Locale locale)` | Sets the locale of this scanner | For more content, you can refer to the API documentation: [
← Prop Track LabelDocker Version Command β†’