I made a scanner, took asked the user to input an int, then a String and then another String.

But after I put in an int and press enter, it skips the 2 String inputs.

Why?
How can I fix it?

Recommended Answers

All 3 Replies

Scanner methods can be tricky. The Scanner buffers input and can block waiting for input.
Or it can save a newline and return it to the nextLine call.

For example if you enter: A word to the wise <PRESS ENTER>
and use next() only "A" is read, and "word to the wise" is left in the buffer.
Your next attempt to get something from Scanner will be to get "word".
nextInt() will fail here.
To clear the buffer, use the nextLine() method.
To test if the next token is an int, use the hasNextInt() method.

Post the code you are having problems with.

Scanner methods can be tricky. The Scanner buffers input and can block waiting for input.
Or it can save a newline and return it to the nextLine call.

For example if you enter: A word to the wise <PRESS ENTER>
and use next() only "A" is read, and "word to the wise" is left in the buffer.
Your next attempt to get something from Scanner will be to get "word".
nextInt() will fail here.
To clear the buffer, use the nextLine() method.
To test if the next token is an int, use the hasNextInt() method.

Post the code you are having problems with.

Thank you.
I don't remember what I was doing, but I wanted an int, then 2 strings, like in the following code.
You sollution worked perfectly:

import java.util.Scanner;

public class mainX
{
	
	public static void main(String[] argv)
	{
		
		Scanner scn = new Scanner(System.in);
		
		int a;
		String b,c;
		
		System.out.println("Int");
		a = scn.nextInt();
		scn.nextLine();
		
		System.out.println("String");
		b = scn.nextLine();
		System.out.println("String2");
		c = scn.nextLine();
		
		System.out.println("A = "+a+", B = "+b+", C = "+c);
		
	}
}

I have a question though.
Some variables are just "int a = 12" while others are "private int a = 12"
Does "int a = 12" make it private?
Or...
: /?

Should add that just "int a = 12" are often seen in the main class, but private int a = 12 in other classes...

Is this because it starts in main, if it needs variables or methods in other variables, it will see its public/private?

So uhm.. does int a make it automatically private or what...?

The private attribute is to keep other classes from being able to see it.
Its not something you need to worry about for a while.

A variable defined inside of a method is local to that method and can not be seen by any code outside of the method. They disappear when the method exits.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.