سؤال

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.

هل كانت مفيدة؟

المحلول

  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

نصائح أخرى

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

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top