nabelekt
nabelekt

Reputation: 159

Reading an integer from the command prompt in Java using Scanner

I can't figure out what I'm doing wrong here.

My code:

import java.util.Scanner;

public class test
  {
    public static void main(String args[])
      {
        Scanner input_scanner = new Scanner(System.in);
        System.out.printf("\nEnter number:");

        int num_shapes = input_scanner.nextInt();

        System.out.printf("\n%d", num_shapes);
      }
  }

Each time the program is run, I enter an integer, press the enter key, am taken to a new line, enter a new integer, and hit the enter key again. The first integer is then displayed.

How can I get it to display the first integer directly after it is entered, without having to enter a second integer?

I've tried it with and without

    input_scanner.nextLine();

following the line containing 'nextInt()', but get the same thing either way.

Any help in resolving this problem is greatly appreciated.

Upvotes: 0

Views: 3822

Answers (1)

user2366923
user2366923

Reputation:

this works perfectly

import java.util.Scanner;

public class mainclass{

   public static void main(String args[])
     {
       Scanner input_scanner = new Scanner(System.in);
       System.out.println("Enter number:");

       int num_shapes = input_scanner.nextInt();

       System.out.println(num_shapes);
     }
 }

Upvotes: 1

Related Questions