A story about misunderstanding how to use java scanner (memo)

table of contents

--Execution environment --Problems and error messages --What you misunderstood --Resolved code --Code explanation --Summary

Execution environment

Java version : 12.0.1 Code description: Text editor (Atom) OS used: windows (It worked on Mac just because of the character code problem) Background of the problem: I wondered if I could make something with what Java beginners learned, and when I tried to write the code myself, an error occurred.

Problems encountered, error messages

The problem I uttered is a program that uses the Scanner class and only re-enters when a key other than a specific input key is input (in this case, I was asked to input 1 or 2). First of all, I thought about the function only and assembled it.

errorFile.java


Scanner sc = new Scanner().nextInt();
while(sc){
  switch(sc){
    case 1:
    //Process 1
    break;
    case 2:
    //Process 2
    break;
    default:
    //Process 3
    break;
  }
}

As you can see, it doesn't work, of course. At this point, you can see that you have made a lot of mistakes in your understanding. Even if you don't understand it, it's more fun to try it, and if you make a mistake, check it each time and solve the error! This is the result of having assembled it with a shallow understanding.

What was misunderstood

At this point, I'll explain what I was thinking about. If you just want to see how to resolve input errors, skip to the code description. I think this will be a snake.

The contents that were misunderstood at this point are mainly the following contents 〇 I thought that the inside of () of while () was a loop condition → Actually, it loops until the condition in () becomes false in boolean

〇 I thought that the Scanner class was a form with Scanner variable name = new Scanner (). NextInt () → Actually, instantiation and acquisition of input elements are separate functions. In other words, new Scanner () and .nextInt () can be separated. In the first place, if it is this sentence, the int type will be acquired by the Scanner, and an extra error will occur ...

〇 I don't understand exception handling → As it is, only number input is supported, and if it is input as a character string, an exception will occur and execution will not be successful. Exception handling is also entered after resolution, but honestly there is still insufficient trial for exception handling.

Code after resolution

Here is a relatively clean code after solving the misunderstandings so far by using questions, materials, books, etc. of great ancestors.

SolutionFile.java


int all = 0;
  while(all == 0){
    try{
      Scanner sc = new Scanner(System.in);
      switch(sc.nextInt()){
        case 1:
          //Process 1
          all +=1;
          break;
        case 2:
          //Process 2
          all +=1;
          break;
        default:
          //Process 3
          break;
      }
    }catch(Exception e){
      //Process 4
    } 
  }

What do you think? At the very least, it works according to my intentions. Do you know the readability, where int all came from, and catch exception handling? I'm writing a code that is said to be, but if it works, it's OK! If so, this is convincing. let's do it.

Code description

Here is a brief explanation of the completed code (SolutionFile.java).

First of all, if you list each scope range (Here, it is written with the range from the beginning to the end)

while // 1
  try // 2
    Scanner // 3
    switch // 4
      case 1:
      case 2:
      default:
    switch
  try 
  catch
  catch
while

Like this while > try == catch > switch > case == default is not it

// 1 Unless you exit while, the process from try to catch will be repeated endlessly. In this condition, the initial value of all is declared first, and the condition is "until all becomes other than 0". In other words, if the value of all is added or subtracted, the loop will end.

// 2 It's a process that may cause an error next. The possibility of an error and the content that you normally want to handle without an error are enclosed in try and the exception is enclosed in catch. And as explained below, catch is a loop in while and does not exit the loop, so after the process in catch is executed, the process returns to the beginning of while again. ..

By the way, I think that if you focus on the fact that an error occurs, it will only be the input of the Scanner, but I tried moving only the switch, but an error occurred. Below is the code to move the switch

Changefile.java


int all = 0;
  while(all == 0){
    try{
      Scanner sc = new Scanner(System.in);
    }catch(Exception e){
      //Process 4
    } 
      switch(sc.nextInt()){
        case 1:
          //Process 1
          all +=1;
          break;
        case 2:
          //Process 2
          all +=1;
          break;
        default:
          //Process 3
          continue;
      }
  }

error:Can't find symbol
switch(sc.nextInt()){
               ^
symbol:Variable sc

It is thought that the reason is that the element of sc is acquired in the switch.

// 3 Here, you only have to enter it. Although it is written in the margin in this code, import java.util.Scanner; Is this description because it is declared first. I don't declare it many times, so just here without declaring import Scanner sc = new java.util.Scanner(System.in); It doesn't seem to be a problem.

// 4 Here, the input contents are acquired and the processing is changed according to the acquired contents. Conditional expressions are possible with if statements, but the switch statement is selected because of its readability and the readability of the code meaning. nextInt() That's why you're asking for numbers. case 1: case 2: So, in addition to each process, to get out of the while loop all += 1 By doing so, the value of all is added by 1. As a result, all = 1, and by satisfying the condition of the loop "until all becomes other than 0", the condition becomes false and the loop is exited.

And when default, that is, a number other than 1 or 2 is input, the process is returned to the beginning of while without changing the loop condition to false by not changing the value of all.

In other words, ask them to enter it many times until 1 or 2 is entered! If you enter another number or string, it will loop endlessly! That is the process.

Summary

The features I wanted to implement If anything other than 1 or 2 is entered, ask for it again It is a function called.

The point I was misunderstanding While condition, Scanner configuration, exception handling

And the content of this article is that I corrected the misunderstanding and solved it. However, although it has started to work, there is still a lot of waste in the code, so there are problems such as cutting waste, trying exception handling, and whether the code is easy for others to read, so I would like to continue trying it in the future. I will. Thank you for your cooperation.

Recommended Posts

A story about misunderstanding how to use java scanner (memo)
How to use Java Scanner class (Note)
A story about trying to operate JAVA File
[Java] How to use Map
[Java] How to use Map
How to use java class
[Java] How to use Optional ②
[Java] How to use removeAll ()
How to use Java Map
How to use Java variables
[Java] How to use Optional ①
How to use Java HttpClient (Get)
How to make a Java container
A memo about the types of Java O/R mappers and how to select them
How to use Java HttpClient (Post)
[Java] How to use join method
How slow is a Java Scanner?
[Processing × Java] How to use variables
[Java] How to create a folder
[Java] How to use LinkedHashMap class
[JavaFX] [Java8] How to use GridPane
How to use class methods [Java]
[Java] How to use List [ArrayList]
How to use classes in Java?
[Processing × Java] How to use arrays
How to make a Java array
How to use Java lambda expressions
[Java] How to use Math class
How to use Java enum type
How to make a Java calendar Summary
A memorandum on how to use Eclipse
Multilingual Locale in Java How to use Locale
[Java] How to use the HashMap class
[Easy-to-understand explanation! ] How to use Java instance
[Introduction to Java] How to write a Java program
[Java] How to use the toString () method
Studying how to use the constructor (java)
[Processing × Java] How to use the loop
How to make a Discord bot (Java)
[Easy-to-understand explanation! ] How to use Java polymorphism
[Java] [Maven3] Summary of how to use Maven3
[Processing × Java] How to use the class
[Processing × Java] How to use the function
[Easy-to-understand explanation! ] How to use ArrayList [Java]
[Java] Learn how to use Optional correctly
[Easy-to-understand explanation! ] How to use Java overload
try-catch-finally exception handling How to use java
[Easy-to-understand explanation! ] How to use Java encapsulation
[Personal memo] How to interact with a random number generator in Java
[Java] How to use substring to cut out a part of a character string
How to use Swift's Codable Super personal memo
[Java] How to use FileReader class and BufferedReader class
[Java] How to use Thread.sleep to pause the program
A story about Java 11 support for Web services
A story about the JDK in the Java 11 era
How to display a web page in Java
How to use Java framework with AWS Lambda! ??
How to convert a solidity contract to a Java contract class
How to use Java API with lambda expression
[Easy-to-understand explanation! ] How to use Java inheritance [Override explanation]
How to use the replace () method (Java Silver)