Search code examples
javaconsoleconsole-input

Java: The right way to make a scanner


First I'm a noob to Java so don't be mad at me if I'm acting stupid - Thanks.

As I said I'm trying to learn Java. Right now I'm trying to learn the right scanner for this mini-game, but I'm getting confused because people tell me to do it in two different ways. I just wan't to know which one to use and where I can use the other one.

First Example:

Scanner input = new Scanner(System.in);

Second Example:

Scanner input = new Scanner(System.in);
String userInput = input.nextLine();

Please tell me how to make the " right " scanner for my mini-game and explain when I should use the other one.

If you know which one to use, another way to create a scanner for this or just wanna share the scanners and how to use them - then please add it as an answer.


Solution

    1. Scanner input = new Scanner(System.in);

    This is calling a scanner and telling that it should be used in the console "System.in".

    1. String userInput = input.nextLine(); This line is taking the value u inserted in the console and saving in a variable named "userInput"

    2. You can add this System.out.println("the inserted value is : " + userInput);

    And it will print in the console the value you inserted