JavaRush /Java Blog /Random EN /Scanner class in Java

Scanner class in Java

Published in the Random EN group
Hello! Our lesson today will be special! Before that, when solving problems and writing programs, the algorithm was simple: we write some code, run the main () method, the program does what is required of it and exits. But now everything will change! Today we will learn how to really interact with the program: we will teach it to react to our actions! Perhaps you already understand what we are getting at. We will devote this lecture to a detailed analysis of one of the classes of the Java language - Scanner. This class is useful if you need to read the data that users enter. Before we move on to the study of the code, tell me, have you ever come across such a device as a scanner? Surely yes. From the inside, the structure of the scanner is quite complex, but the essence of its work is quite simple: it reads the data that the user enters into it (for example, a passport or insurance policy) and stores the read information in memory (for example, in the form of an image). So here it is today you will create your own scanner! Of course, he will not cope with documents, but with textual information - quite well :) Let's go!Scanner class - 1

Java Scanner Class

The first and most important thing we need to get acquainted with is the class java.util.Scanner. Its functionality is very simple. He, like a real scanner, reads data from the source that you specify for him. For example, from a string, from a file, from a console. Then he recognizes this information and processes it as needed. Let's take the simplest example:
public class Main {

   public static void main(String[] args) {

       Scanner scanner = new Scanner("I love you, Petra creation,\n" +
               "I love your stern, slim look,\n" +
               "Neva sovereign current,\n" +
               "Coastal granite");
       String s = scanner.nextLine();
       System.out.println(s);
   }
}
We have created a scanner object and specified a data source for it (a string with text). The method nextLine()accesses the data source (our text with a quatrain), finds the next line there, which it has not yet read (in our case, the first one) and returns it. After that we output it to the console: Output to the console:

Люблю тебя, Peterа творенье,
We can use the method nextLine()multiple times and output the entire piece of the poem:
public class Main {

   public static void main(String[] args) {

       Scanner scanner = new Scanner("I love you, Petra creation,\n" +
               "I love your stern, slim look,\n" +
               "Neva sovereign current,\n" +
               "Coastal granite");
       String s = scanner.nextLine();
       System.out.println(s);
       s = scanner.nextLine();
       System.out.println(s);
       s = scanner.nextLine();
       System.out.println(s);
       s = scanner.nextLine();
       System.out.println(s);
   }
}
Each time our scanner will take one step forward and read the next line. The result of the program is output to the console:

Люблю тебя, Peterа творенье,
Люблю твой строгий, стройный вид,
Невы державное теченье,
Береговой ее гранит
As we have already said, the data source for the scanner can be not only a string, but also, for example, a console. Important news for us: if earlier we only displayed data there, now we will enter data from the keyboard! Let's see what else the Scanner class can do :
public class Main {

   public static void main(String[] args) {

       Scanner sc = new Scanner(System.in);
       System.out.println("Enter the number:");

       int number = sc.nextInt();

       System.out.println("Thank you! You entered a number" + number);

   }
}
The method nextInt()reads and returns the entered number. In our program, it is used to assign a value to a variable number. This is more like a real scanner! The program asks the user to enter any number in a string. After the user has done this, the program thanks him, displays the result of his work on the console, and ends. But we still have one major problem. The user can make a mistake and enter something wrong. Here is an example where our current program will stop working:
public class Main {

   public static void main(String[] args) {

       Scanner sc = new Scanner(System.in);
       System.out.println("Enter the number:");

       int number = sc.nextInt();

       System.out.println("Thank you! You entered a number" + number);

   }
}
Let's try to enter the string "CodeGym" instead of a number: Console output:
Enter the number:
CodeGym
Exception in thread "main" java.util.InputMismatchException
  at java.util.Scanner.throwFor(Scanner.java:864)
  at java.util.Scanner.next(Scanner.java:1485)
  at java.util.Scanner.nextInt(Scanner.java:2117)
  at java.util.Scanner.nextInt(Scanner.java:2076)
  at Main.main(Main.java:10)

Process finished with exit code 1
Oops, that's bad -_- To avoid situations like this, we need to come up with a way to validate the data that the user enters. For example, if the user enters anything other than a number, it would be nice to display a warning in the console that the entered information is not a number, and if everything is in order, display a confirmation text. But for this, we actually need to “look into the future” - find out what is next in our stream. Can Scanner in Java do this? How else can he! And for this, it has a whole group of methods: hasNextInt()- the method checks whether the next portion of the entered data is a number or not (returns true or false, respectively). hasNextLine()- checks if the next piece of data is a string. hasNextByte(), hasNextShort(), hasNextLong(), hasNextFloat(),hasNextDouble()- all these methods do the same for other data types. Let's try to modify our number reading program:
public class Main {

   public static void main(String[] args) {

       Scanner sc = new Scanner(System.in);
       System.out.println("Enter the number:");

       if (sc.hasNextInt()) {
           int number = sc.nextInt();
           System.out.println("Thank you! You entered a number" + number);
       } else {
           System.out.println("Sorry, but this is clearly not a number. Restart the program and try again!");
       }

   }
}
Now our program checks if the next character entered is a number or not. And only if it is, displays a confirmation. If the input did not pass the test, the program notices this and asks you to try again. Essentially, you can talk to the Scanner object and know ahead of time what type of data you should expect. “Hey, scanner, what's next? Number, string, or something else? Number? And what - int, short, long? Such flexibility gives you the opportunity to build the logic of your program depending on the behavior of the user. Another important method worth paying attention to is useDelimiter(). This method is passed the string you want to use as the delimiter. Scanner class - 2For example, we suddenly became fascinated with Japanese poetry and decided to count several haiku of the great poet Matsuo Basho with the help of a scanner. Even if three different verses are given to us in one clumsy line, we can easily separate them and format them beautifully:
public class Main {
   public static void main(String[] args) {
       Scanner scan = new Scanner("On a Bare Branch" +
               "Raven sits alone.'" +
               "Autumn evening." +
               "''***''" +
               "There's such a moon in the sky,'" +
               "Like a tree cut down at the root:'" +
               "A fresh cut turns white." +
               "''***''" +
               "How the river has overflowed!" +
               "The heron wanders on short legs,'" +
               "Knee-deep in water.");

       scan.useDelimiter("'");

       while (scan.hasNext()) {
           System.out.println(scan.next());
       }

       scan.close();
   }
}
We use the useDelimeter() method of the Scanner class as the line separator : it is responsible for dividing the incoming data into parts. In our case, to separate strings, a single quote ( "'" ) is passed and used as an argument . The text following this quotation mark is displayed on a new line because in the while loop we are using the println() method of the System class to read the data. As a result, we will have a beautiful output in the console, just like in books:
На голой ветке
Ворон сидит одиноко.
Осенний вечер.

*** 
 
В небе такая луна,
Словно дерево спилено под корень:
Белеет свежий срез.

*** 
 
Как разлилась река!
Цапля бредет на коротких ножках,
По колено в воде.
In the same example, there is another method that you should definitely pay attention to - close(). Like any object that works with I / O streams, the scanner must be closed when it completes its work so that it no longer consumes the resources of our computer. Never forget the method close()!
public class Main {

   public static void main(String[] args) {

       Scanner sc = new Scanner(System.in);
       System.out.println("Enter the number:");

       int number = sc.nextInt();

       System.out.println("Thank you! You entered a number" + number);

       sc.close();//Now we did everything right!

   }
}
That's all! As you can see, the Scanner class is quite easy to use and very useful! :)
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION