How would you test Scanner input in Java?

So I am new to Replit. I am trying to make a test that test input from the keyboard and then a final print statement. However, my test keeps getting stuck at the first Print statement I ask. Even though my output is correct. Just curious on how to go about testing Scanner input?

So like:

System.out.println("What is your name?");
String name = input.nextLine();

How do I get it to recognize both the statement and the return?

Any help is appreciated. Thanks in advance!

You are viewing a single comment. View All


When you use nextLine(), Java will catch everything the user types until he presses enter/return.

What do you mean by testing the Scanner? What problem do you have?

To get user input, we first need to import the Scanner library in the top of your Java file:

Then, in the main method (or wherever), create what we call an instance of Scanner from the Scanner class:

Notice Sounds similar to how we print stuff in Java but reversed? We pass this to Scanner.
Then we can ask the user for input. Let's first tell the user what to write:

System.out.print will not create a new line while System.out.println will.
Now to get the user input. To get a String input, we use next(). To get an int input, we use nextInt(), and so on with other data types. Another way to get a String is with what you're doing right now: nextLine(), which basically collects whatever the user typed before he pressed enter. Let's do it:

Now we can use the variable name:

This is what the program looks like as a whole:



Thank you for your response. I understand how Scanner works but I just can't figure it out if someone enters different names. So I just told the students to input a certain name. If you know how I can test it with different inputs that would be helpful!


@Tanisi90 hmm... not sure I know what you mean. Is it that you don't want duplicate names?