In this chapter we will discuss the scanning input.
Because most of the time we need to read the corresponding text from the text file, and then processing, in the input to other places, this time we need to describe the following scan input.
1. The usual 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 ("raylee\n31\ n1.77 "));p ublic 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)
Above is the usual situation, we use reader to read a piece of text, and then through the ReadLine to read the string, and then strongly to the various types, and finally will be placed in an object.
But there are a lot of steps to this, and it's very easy to make mistakes in the process.
So we end the scanner below, which will reduce some of the above steps.
Also, there is no judgment operation in reader, so it is very easy to get a run-time exception.
2. Using scanner
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 ("raylee\n31\ n1.77 "));p ublic 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 ());}}}
By scanner we have reduced the process of strong transfer and made the code cleaner and cleaner.
You can also use the Hasnext method to determine if there are any other characters, while Hasnext can also contain other parameters to improve flexibility.
Summary: This section describes the scanning input and describes some of the usage of scanner.
This chapter is here, thank you.
-----------------------------------
Directory
Understanding java-11.5 Scan Input (1)-Introduction