Ask coding questions

← Back to all posts
How would you test Scanner input in Java?
Tanisi90 (0)

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!

Comments
hotnewtop
codingjlu (225)

Edit

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:

import java.util.Scanner;

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

Scanner input = new Scanner(System.in);

Notice System.in. 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("Enter your name: ");

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:

String name = input.nextLine(); // Whatever the user types will be inside the name variable

Now we can use the variable name:

System.out.println(name);

This is what the program looks like as a whole:

import java.util.Scanner;
public class Main {
   public static void main(String[] args) {
      Scanner input = new Scanner(System.in);
      System.out.print("Enter your name: ");
      String name = input.nextLine();
      System.out.println("Hello, " + name + "!");
   }
}
Tanisi90 (0)

@codingjlu

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!

codingjlu (225)

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