0

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.

Community
  • 1
  • 1
Landscape
  • 249
  • 1
  • 2
  • 13
  • In both examples you are making only one scanner and to the same stream (line 1).. In the second case you are just Using the scanner to read a line from the console and store it in a String variable (line 2)... As for your second question, you can use the same scanner as long as you want data from the same stream... – TheLostMind Jan 23 '14 at 14:38

2 Answers2

0
  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

Sembrano
  • 1,127
  • 4
  • 18
  • 28
0

If I'm reading your question correctly, both of your examples are same as far as creating a Scanner object is concerned. Only difference is that second example is also storing the nextLine of input into a String variable called userInput.

Look here to understand Scanner class better: http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

anshulv
  • 132
  • 1
  • 1
  • 9