1

I've been storming ahead with my Java work at University (I've never done Java prior to this) but I'm stuck with inputs a little bit. The task is to write a basic program that allows the user to input their name, house number, road name and town but when it gets to inputting the road name, it seems to skip and doesn't allow you to enter anything for town.

Now, I've tried a flush buffer but that didn't work since it just overwrites what was input. For example, I put the flush buffer after the road name input and that input would then be ignored.

The problem could also be that white space is breaking things despite me using nextLine and not next.

Here's my code;

import java.util.*;

public class AddressProj {

    public static void main(String[] args)
    {
        Scanner myKeyboard = new Scanner(System.in);

        System.out.printf("Please input your surname: ");
        String name = myKeyboard.nextLine();

        System.out.printf("Please input your house number: ");
        int houseNumber = myKeyboard.nextInt();

        System.out.printf("Please input your road name: ");
        String roadName = myKeyboard.nextLine();
        myKeyboard.nextLine(); //Flush buffer

        System.out.printf("Please input your town: ");
        String town = myKeyboard.nextLine();

        System.out.printf("Surname: " + name + "\nHouse Number: " + houseNumber + "\nRoad Name: " + roadName + "\nTown: " + town + "\n");
    }
}
8
  • What on earth do you mean by a 'flash buffer'? Commented Jan 26, 2014 at 22:55
  • @bmargulies flush a buffer, I suppose. Commented Jan 26, 2014 at 22:55
  • @bmargulies uh, apologies. flush buffer. it's getting late. Commented Jan 26, 2014 at 22:58
  • I know flushing the buffer is only usable after entering an integer which is why I'm rather stuck on what to do here. Commented Jan 26, 2014 at 23:01
  • why do you think that a call to nextLine() is flushing a buffer? My advice is not to connect a scanner directly to System.in. But more generally, this sort of Console IO is very rare in modern practical programming. Commented Jan 26, 2014 at 23:01

1 Answer 1

2

nextInt() does not read an entire line. Just an int. So the NL you are entering to end the house number is left to be eaten by the next thing.

I strongly recommend something more like:

InputStreamReader isr = new InputStreamReader(System.in, "utf-8");
BufferedReader reader = new BufferedReader(isr);

Then, for each item:

reader.readLine();

to obtain the user's input, and then parse as needed with things like Integer.parseInt.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.