Get started with java-11.5 Scanning Input (1)-Introduction
In this section, we will discuss the scanning input.
Most of the time, we need to read the corresponding text from the text file and process it. When the input is somewhere else, we need to scan the input as described below.
1. General situation
package com.ray.ch11;import java.io.BufferedReader;import java.io.IOException;import java.io.StringReader;import java.util.Scanner;public class Test {private BufferedReader input = new BufferedReader(new StringReader(raylee311.77));public BufferedReader getInput() {return input;}public void setInput(BufferedReader input) {this.input = input;}public static void main(String[] args) throws IOException {Test test = new Test();System.out.println(name: + test.getInput().readLine());System.out.println(age:+ Integer.parseInt(test.getInput().readLine()));System.out.println(height+ Double.parseDouble(test.getInput().readLine()));System.out.println(height+ Double.parseDouble(test.getInput().readLine()));}}
Output:
Name: raylee
Age: 31
Height1.77
Exception in thread main java. lang. NullPointerException
At sun. misc. FloatingDecimal. readJavaFormatString (FloatingDecimal. java: 989)
At java. lang. Double. parseDouble (Double. java: 510)
At com. ray. ch11.Test. main (Test. java: 29)
The above is the general situation. We use reader to read a piece of text, then read the string through readline, and then convert it into various types, and finally put it in a certain object.
However, such an operation involves many steps and is prone to errors during processing.
Therefore, we end the restore operation below, which will reduce some of the above operation steps.
In addition, the reader does not judge the operation, so it is easy to encounter exceptions during running.
2. Use Logging
package com.ray.ch11;import java.io.BufferedReader;import java.io.IOException;import java.io.StringReader;import java.util.Scanner;public class Test {private BufferedReader input = new BufferedReader(new StringReader(raylee311.77));public BufferedReader getInput() {return input;}public void setInput(BufferedReader input) {this.input = input;}public static void main(String[] args) throws IOException {Test test = new Test();Scanner scanner = new Scanner(test.getInput());if (scanner.hasNext()) {System.out.println(name: + scanner.nextLine());}if (scanner.hasNext()) {System.out.println(age: + scanner.nextInt());}if (scanner.hasNext()) {System.out.println(height: + scanner.nextDouble());}}}
We use compaction to reduce the strong conversion process and make the code more clean and concise.
In addition, the hasNext method can be used to determine whether there are other characters in the future, and other parameters can be included in hasNext to improve flexibility.
Summary: This section describes the scanning input and usage of the scanner.