i want to know how Scanner code works in Java - java

it's my first time to ask in this community
first, please excuse my poor english in advance
i want to know how Scanner code works
Scanner scanner = new Scanner(System.in); ------Call it "A" for convenience
System.out.print("first number:");
String strNum1 = scanner.nextLine();
System.out.print("second number:"); -----Call it "B" for convenience
String strNum2=scanner.nextLine();
int num1 = integer.parseInt(strNum1); ---- Call it "C" for convenience
int num2 = integer.parseInt(strNum2);
int result = num1 + num2;
System.out.println("Add result: " + result);
Question is about Process of
in the moment i input some number in Console after [code above] is implemented
how [code above] interact(?) with result in Console
For example , when i input code above, run it
and i input some number in console
(1) input 1 -> output in console - "first number:1"
(2) input 3 -> output in console - "first number:1" "Second number:3" "Result: 4"
i can see this
So,
does it mean, when the process up to (1) is input, Progress to "A" shows up?
if it's right, that 'scanner.nextLine()' is input at first as "1" Is the process of (1)
But, although the variable 'strNum1' is not run by 'System.out.println()'
Why can i see this number "1" ??
And,
Why doesn't System.out.print("first number") appears at first,
unless i input some number like "1"
in connection with String strNum1 = scanner.nextLine();

You dont need to get a string from the user and after that parse it to int If you only want to connect two numbers , you can get a int from the user and use with scanner.nextInt() , This will save you code lines and efficiency.
Scanner scanner = new Scanner(System.in);
int num1 = scanner.nextInt();
int num2 = scanner.nextInt();
int result = num1 + num2;
System.out.println(num1 + " + " + num2 + " = "+ result);
When you working with string you need to use with scanner.nextLine(); or if you work with a number that start with 0(like maybe id) string is the right thing , because int cant be start with 0.

Okay, let's dig in it (yes, line by line).
You create the Scanner object which takes as input the common input stream provided by the System.in, in that case the console itself.
Then, you are calling System.out.print which is different from System.out.println
System.out.print will simply append to the current state of the console the value you provided
Scanner gets call in using the nextLine() methods, this block the process until some input is inserted inside the console terminal, this is how usually the console works, you input something, press enter and it gets executed. More or less, it's the same in that case, scanner wait until you provide a line separator (press enter).
The exact same stuff happens for the scanner B
The numbers gets parsed and in the end their output is appended to the terminal with System.out.println()
Let's summarise:
Scanner block the thread until it receives an input, then it gets parsed and the normal flow of the routine goes on. A Scanner breaks its input into tokens using a delimiter pattern, in that case of nextLine() the delimiter pattern is the System.lineSeparator();

Related

some questions about java Scanner

enter image description here
}
Why does the code on line 6 have the same effect on line 8? Is there no distinction between the starting point of this while loop?
Also, you should follow this tips to use the Scanner properly:
Mixing any nextXXX method with nextLine from the Scanner class for user input, will not ask you for input again but instead result in an empty line read by nextLine.
To prevent this, when reading user input, always only use nextLine. If you need an int, do
int value = Integer.parseInt(scanner.nextLine());
instead of using nextInt.
Assume the following:
Scanner sc = new Scanner(System.in);
System.out.println("Enter your age:");
int age = sc.nextInt();
System.out.println("Enter your name:");
String name = sc.nextLine();
System.out.println("Hello " + name + ", you are " + age + " years old");
When executing this code, you will be asked to enter an age, suppose you enter 20.
However, the code will not ask you to actually input a name and the output will be:
Hello , you are 20 years old.
The reason why is that when you hit the enter button, your actual input is
20\n
and not just 20. A call to nextInt will now consume the 20 and leave the newline symbol \n in the internal input buffer of System.in. The call to nextLine will now not lead to a new input, since there is still unread input left in System.in. So it will read the \n, leading to an empty input.
So every user input is not only a number, but a full line. As such, it makes much more sense to also use nextLine(), even if reading just an age. The corrected code which works as intended is:
Scanner sc = new Scanner(System.in);
System.out.println("Enter your age:");
// Now nextLine, not nextInt anymore
int age = Integer.parseInt(sc.nextLine());
System.out.println("Enter your name:");
String name = sc.nextLine();
System.out.println("Hello " + name + ", you are " + age + " years old");
The nextXXX methods, such as nextInt can be useful when reading multi-input from a single line. For example when you enter 20 John in a single line.

Java, How do I validate input when using scanner?

I am currently working on Java code. Basically, the int input works. However, if I type in a character, the whole system crashes. My question is as to what needs to be changed in the below code in order for the user to receive a message stating that only an int is the valid input, and to try again if they input a character.
do {
System.out.println("How many players would like to participate in this game?\t(2-4 players)");
numberOfPlayers = in.nextInt();
} while(in.hasNextInt());
numberOfPlayers = in.nextInt();
I personally prefer to use a while loop for this sort of thing rather than the do/while. Not that there is anything wrong with the do/while, I just feel it's more readable to use the while loop.
I agree with others here, accept String digits from the User instead of Integer. In my opinion it saves you other possible problems down the road and you have no need to purposely apply a try/catch mechanism should the User supply an invalid entry. It also allows you to easily apply a mechanism to quit the application which, again IMHO, should be made available to all Console app's.
You've got your answer for carrying out the task using a do/while loop but I would like to show you another way to do this sort of thing:
Scanner in = new Scanner(System.in);
String ls = System.lineSeparator();
int numberOfPlayers = 0;
String userInput = "";
while (userInput.equals("")) {
// The Prompt to User...
System.out.print("How many players would like to participate in this game?" + ls
+ "2 to 4 players only (q to quit): --> ");
userInput = in.nextLine();
// Did the User enter: q, quit (regardless of letter case)
if (userInput.toLowerCase().charAt(0) == 'q') {
// No, the User didn't...
System.out.println(ls + "Quiting Game - Bye Bye.");
System.exit(0); // Close (exit) the application.
}
/* Did the User supply a string representation of a numerical
digit consiting of either 2, 3, or 4. */
if (!userInput.matches("[234]")) {
// No, the User didn't...
System.out.println("Invalid input! You must supply a number from 2 to 4 "
+ "(inclusive)." + ls + "Try again..." + ls);
userInput = "";
continue; // Loop again.
}
// Convert numerical string digit to an Ingeger value.
numberOfPlayers = Integer.parseInt(userInput);
}
System.out.println(ls + "The Number of players you provided is: --> "
+ numberOfPlayers);
You will notice that the Scanner#nextLine() method is used to accept User input as a String. This now means that we need to validate the fact that a string representation of a Integer numerical digit (2 to 4 inclusive) was supplied by that User. To do this you will notice that I used the String#matches() method along with a small Regular Expression (RegEx) which consists of the following string: "[234]". What this does in conjunction with the String#matches() method is it checks to see if the string value in the userInput variable contains either a single "2", a single "3", or a single "4". Anything else other than any one of those three digits will display this message:
Invalid input! You must supply a number from 2 to 4 (inclusive).
Try again...
and, force the User make yet another entry.

Is it possible to create input scanner between String value Java Console?

I try to custom my Java Console Application, but I have a problem when I try to show it in Command Prompt will appear input Scanner between String...
int a;
Scanner scan = new Scanner(System.in);
System.out.println("Input value of a: " + (a = scan.nextInt()) + " !");
Anyone can resolve this problem, help me....
thank you
1. First of all, your code runs as it is coded not as it is expected.
As your output is blank, and you are wandering why the prompt has not come yet for asking the user input, then let me tell you one thing, that it is actually asking you to enter some input right there. As soon as, you will enter, you shall see the next line of your output will be..
Input value of a: (whatEverYouEntered)
So your final output would be, (strictly as per your code..)
F:/SMK/oop>javac Main.java
F:/SMK/oop>5 (assumed you type 5 and press enter)
F:/SMK/oop>Input value of a: 5
2. If you think that your code should print Input value of a: line fist and then you will enter the value, then you'll have to make changes as below.
int a;
Scanner scan = new Scanner(System.in);
System.out.print("Input value of a: ");
a = scan.nextInt();
3. And if you are really curious about the reason why your code was behaving like that..then read this..
I would say, change your code as stated below and then run, you might get a hint, otherwise I'll explain later.
public static void main(String[] s) {
int a = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Input value of a: " + (a = new Main().getVal()) + " !");
System.out.println("A = " + a);
}
public int getVal(){
System.out.println("getVal called first.");
return 5;
}
See the output now, it shall be.
F:/SMK/oop>javac Main.java
F:/SMK/oop>getVal called first.
F:/SMK/oop>Input value of a: 5
The reason is, when JVM interprets System.out.println("Input value of a: " + (a = new Main().getVal()) + " !"); this as a single statement, and to execute it must be complete... so how will it get complete?--> By assigning the value of a. and to do so, it must call getVal() function before printing anything, right?
Exactly the same is happening in your code, as your print statement will be executed after the call of scan.nextInt() and nextInt() immediately asks for user input without showing any message in console. And once the input is provided, it will assign the value to a and now the print statement is actually complete and ready to execute. And hence, you would see the print output after the input prompt.
Hope it gives you good idea about java and programming language as well.
Happy coding :)

Error using InputStream.skip()

I am looking for something similar to C++'s cin.ignore() function.
I am new to JAVA and I trying something like this
Scanner user_input = new Scanner(System.in) ;
int num1, num2 ;
System.out.print("\n Enter the two numbers : " +
"\n number 1 : ") ;
num1 = user_input.nextInt() ;
System.out.print("\n Number 2 : ") ;
num2 = user_input.nextInt() ;
After this line when I am trying to take a String input from the user like this
String choice;
choice = user_input.nextLine() ;
It just ignores it continues to the next line.
I tried using InputStream.skip(long) ; just before taking the String input from the user. I read from here that is equivalent to C++'s cin.ignore()
What is the mistake that I am making?
Oh I included this too import java.io.InputStream;
EDIT : I was asking for whether I could use InputStream.skip() here.
"It just ignores it continues to the next line."
When you say num2 = user_input.nextInt() ; You press the return (enter) key at the end as well which doesn't get read along with num2 and hence when you say choice = user_input.nextLine(); it (return key) gets consumed with this method call and hence you see that it ignored your method call to read a line.
You could resolve this in two ways:
You could read whole line and convert into integer while reading num2 like
num2 = Integer.parseInt(user_input.nextLine());
Or just to consume return key press, you could add additional call of readline like:
user_input.nextLine();//consume enter key press
choice = user_input.nextLine();

How do i declare and read values into integer values?

I'm really new to java and i'm taking an introductory class to computer science. I need to know how to Prompt the user to user for two values, declare and define 2 variables to store the integers, and then be able to read the values in, and finally print the values out. But im pretty lost and i dont even know how to start i spent a whole day trying.. I really need some help/guidance. I need to do that for integers, decimal numbers and strings. Can someone help me?
You can do this by using Scanner class :
A simple text scanner which can parse primitive types and strings using regular expressions.
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.
For example, this code allows a user to read a number from System.in:
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
int j = scan.nextInt();
System.out.println("i = "+i +" j = "+j);
nextInt() : -Scans the next token of the input as an int and returns the int scanned from the input.
For more.
or to get user input you can also use the Console class : provides methods to access the character-based console device, if any, associated with the current Java virtual machine.
Console console = System.console();
String s = console.readLine();
int i = Integer.parseInt(console.readLine());
or you can also use BufferedReader and InputStreamReader classes and
DataInputStream class to get user input .
Use the Scanner class to get the values from the user. For integers you should use int, for decimal numbers (also called real numbers) use double and for strings use Strings.
A little example:
Scanner scan = new Scanner(System.in);
int intValue;
double decimalValue;
String textValue;
System.out.println("Please enter an integer value");
intValue = scan.nextInt(); // see how I use nextInt() for integers
System.out.println("Please enter a real number");
decimalValue = scan.nextDouble(); // nextDouble() for real numbers
System.out.println("Please enter a string value");
textValue = scan.next(); // next() for string variables
System.out.println("Your integer is: " + intValue + ", your real number is: "
+ decimalValue + " and your string is: " + textValue);
If you still don't understand something, please look further into the Scanner class via google.
As you will likely continue to run into problems like this in your class and in your programming career:
Lessons on fishing.
Learn to explore the provided tutorials through oracle.
Learn to read the Java API documentation
Now to the fish.
You can use the Scanner class. Example provided in the documentation.
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();

Categories