Home java Strange behavior of scanner.nextInt ()

Strange behavior of scanner.nextInt ()

Author

Date

Category

Hello everyone. I am a completely newbie and have been puzzling over this question all morning.
For example, a simple program that writes questions and answers to an array:

import java.util.Scanner;
class proba {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.println("Input the number of cards:");
        int skolko = scan.nextInt();
        String[] vopros = new String[skolko];
        String[] otvet = new String[skolko];
        int i = 0;
        for (; i < skolko; i++) {
            System.out.println("The card #" + (i + 1) + ":");
            vopros[i] = scan.nextLine();
            System.out.println("The definition of the card #" + (i + 1) + ":");
            otvet[i] = scan.nextLine();
        }
    }
}

If the variable int skolkois written into the program (int skolko = 3;), then the program works adequately and asks for a question / answer exactly 3 times in turn.

The card #1:
<<
The definition of the card #1:
<<

If the variable skolkois entered via int skolko = scan.nextInt();, then the program first asks for a number, and then immediately outputs

The card #1:
The definition of the card #1:
<

that is, no value is entered after The card #1:and an empty value is assigned to card #1("").

Why is that?


Answer 1, authority 100%

Cause of the problem:

First you need to understand how scanner.nextLine()works. It reads the line (in fact, it moves through the byte array from InputStreamconsole, i.e. from System.in) to its end (to \n, or \r\n, depending on the environment), after which it stops at the first character after the end-of-line character (s), and everything that it read (except for the character (s) it returns the end of the line as the result of the call).

Before for, you call scanner.nextInt(), which reads a number from the InputStreamconsole and stops its pointer at the first character after the end numbers, in your case, because after entering the number you pressed enteryou have the line feed character (s) there.

At the first iteration of for, scanner.nextLine()is called, which, according to the above mechanism, reads all characters to the end of the line and stops, but in your case it was already at the end-of-line character, so it just moved its pointer to the first character after the end-of-line character (s) and stopped, and as a result of its call returned an empty string ("").

Problem solution:

The easiest way for you is to write scanner.nextLine();immediately after calling scanner.nextInt();to translate scannerto the next line (the pointer in the InputStreambeing read is shifted to the first character after the character (s) of the end of the current line), where the input of the contra line has not yet been performed (since its input has not yet been was implemented).

An example of an alternate use case for nextInt:

Based on the questions from the comments, I will give an example that explains how you can still work with the nextIntmethod:

public class Example {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter three numbers on one line, separated by whitespace:");
        System.out.println(scanner.nextInt());
        System.out.println(scanner.nextInt());
        System.out.println(scanner.nextInt());
    }
}

As you can see, it is not necessary to execute nextLineafter each nextInt, you can read several numbers at a time from one line, separated by whitespace characters.

Recommendations:

Within Java, for naming classes according to naming conventions UpperCamelCase style (for example, Proba), not lowerCamelCase, as you have (Proba).

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions