-1

I am looking for something similar to C++'s cin.ignore() function.

I am new to JAVA and I trying something like this

Scanner user_input = new Scanner(System.in) ;   
int num1, num2 ; 

System.out.print("\n Enter the two numbers : " +
                 "\n number 1 : ") ;    
num1 = user_input.nextInt() ; 

System.out.print("\n Number 2 : ") ; 
num2 = user_input.nextInt() ;

After this line when I am trying to take a String input from the user like this

String choice; 
choice = user_input.nextLine() ;

It just ignores it continues to the next line.

I tried using InputStream.skip(long) ; just before taking the String input from the user. I read from here that is equivalent to C++'s cin.ignore()

What is the mistake that I am making?

Oh I included this too import java.io.InputStream;

EDIT : I was asking for whether I could use InputStream.skip() here.

Community
  • 1
  • 1
Tasdik Rahman
  • 2,160
  • 1
  • 25
  • 37

1 Answers1

0

"It just ignores it continues to the next line."

When you say num2 = user_input.nextInt() ; You press the return (enter) key at the end as well which doesn't get read along with num2 and hence when you say choice = user_input.nextLine(); it (return key) gets consumed with this method call and hence you see that it ignored your method call to read a line.

You could resolve this in two ways:

  • You could read whole line and convert into integer while reading num2 like

    num2 = Integer.parseInt(user_input.nextLine());
    
  • Or just to consume return key press, you could add additional call of readline like:

    user_input.nextLine();//consume enter key press
    choice = user_input.nextLine();
    
SMA
  • 36,381
  • 8
  • 49
  • 73