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 this, 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 truly interact with the program: we will teach it to respond to our actions! You may already understand where we are going with this. We will devote this lecture to a detailed analysis of one of the Java language classes – Scanner. This class will be useful if you need to read data that users enter. Before we move on to learning the code, tell me, have you ever come across such a device as a scanner? Surely yes. The internal 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, today you will create your own scanner! Of course, he can’t handle documents, but he can handle text 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. Like a real scanner, it reads data from the source you specify for it. For example, from a line, from a file, from the console. Then it recognizes this information and processes it as needed. Let's give 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 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 quatrains), finds there the next line that it has not yet read (in our case, the first) and returns it. After which we output it to the console: Console output:

Люблю тебя, Peterа творенье,
We can use the method nextLine()several 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 previously we only output 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 looks more like a real scanner! The program asks the user to enter any number into a line. After the user has done this, the program thanks him, displays the result of its work on the console and ends. But we still have one serious problem. The user may make a mistake and enter something wrong. Here's an example of when our current program would 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 entering the string “JavaRush” instead of a number: Console output:
Enter the number:
JavaRush
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, everything is bad -_- To avoid such situations, we need to come up with a way to validate the data that the user enters. For example, the user enters anything other than a number, it would be nice to display a warning in the console that the information entered is not a number, and if everything is in order, display confirmation text. But to do this, we actually need to “look into the future” - find out what’s next in our flow. Can Scanner in Java do this? How 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 whether 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 change our program to read numbers:

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 whether the next character entered is a number or not. And only if it is, it displays a confirmation. If the input does not pass the test, the program notices this and asks you to try again. Essentially, you can communicate with the Scanner object and know in advance what type of data to expect. “Hey, scanner, what's next? Number, string, or something else? Number? And which one - int, short, long?” This flexibility gives you the opportunity to build the logic of your program depending on user behavior. Another important method that is worth paying attention to is useDelimiter(). This method is passed the string that you want to use as the delimiter. For example, we suddenly became interested in Japanese poetry and decided to use the scanner to read several haiku of the great poet Matsuo Basho. Even if three different verses are given to us in one clumsy line, we can easily separate them and format them nicely:

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 a line separator : it is responsible for dividing the incoming data into parts. In our case, a single quote ( "'" ) is passed as an argument and used to separate strings . The text following this quote appears 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 the books:
На голой ветке
Ворон сидит одиноко.
Осенний вечер.

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

*** 
 
Как разлилась река!
Цапля бредет на коротких ножках,
По колено в воде.
In the same example, there is one more method that you should definitely pay attention to - close(). Like any object that works with I/O streams, the scanner should be closed when it completes its work so that it no longer consumes our computer's resources. 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