The Scanner class is a class included in the java.util package.
It is mainly used for inputting console screens and reading csv files.
I'm tired of reading the explanation, so I'll go to the example.
First, let's take a look at the frequently used type specification input. Code screen
Console screen
Yes, it looks like this. By the way, this is incomplete, but it is easy to see, so I will explain it once.
As for the order ① First, import the Scanner class. The import rule is ```import package name.class name` ``. ② Next, [instantiate] the imported Scanner class (https://techacademy.jp/magazine/17543). System.in is the console input (standard input).
③ Create a variable of the specified type. Get the value there with the nextInt () method of the Scanner class and initialize it.
`Other types include nextByte, nextShort, nextLong, nextFloat, nextDouble, and nextBoolean. There is only a char type method. There are next and nextLine in the character string. ``
④ Finally, you need to close the Scanner with the close method. Be careful not to close it as it will cause an unexpected error.
The fact that it is incomplete means that an error will occur if you input anything other than int type on the above console input screen. Console screen
If you try to perform an unexpected process in this way, an error will occur, so you should expect the process in this case. (I don't understand Japanese)
The try-catch syntax covers the handling of possible exceptions. The procedure is the same as the if statement.
Handling that may cause exceptions;
}catch(<Exception class> <Variable name>){
What to do when an exception occurs;
}```
is. This time
code
<img width="704" alt="スクリーンショット 2020-05-26 15.24.23.png " src="https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/253875/3d2e96d6-1b6e-e20e-c542-17ac611c6e2d.png ">
Console screen
<img width="469" alt="スクリーンショット 2020-05-26 15.24.35.png " src="https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/253875/babbcf5c-907a-a78f-3fa4-f1358352f71f.png ">
As a caveat
①
You need to import the exception handling class.
If you look closely, you can see that ```import java.util.InputMismatchException; // `` `for exception handling has been added at the top.
②
#### **`System.out.println("The entered number is" + num + "is.");Try-If you put it in the catch statement, it will process even if it is an exception.(This time the scope of num is inside the try block, so an error occurs)`**
This is unpleasant ~.
I tried to summarize how to use the super basic Scanner. The following is a compilation of code articles that loop input until normal processing is done.
Recommended Posts