Error using InputStream.skip() - java

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();

Related

i want to know how Scanner code works in 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();

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.

How to check if the next 3 input is an int by using Scanner.hasNextInt() and loop only in java

How can I check if the next three input user is giving is an int value,
like let's say there is three variables,
var1
var2
var3
And I am taking input as,
Scanner sc = new Scanner (System.in);
var1 = sc.nextInt();
var2 = sc.nextInt();
var3 = sc.nextInt();
Now if I want to use while(sc.hasNextInt()) to determine if the next input is an int or not then it will only check if the next input for var1 is int or not and won't check for the other to variables, var2, var3. One thing can be done by using while loop with if (condition). For example,
Scanner sc = new Scanner (System.in);
while (sc.hasNextInt()) {
var1 = sc.nextInt();
if (sc.hasNextInt()) {
var2 = sc.nextInt();
if (sc.hasNextInt()) {
var3 = sc.nextInt();
}
}
}
But this looks lengthy and needs a lot to write. For similar issue I have seen for Language C there is a method for scanf() which can do the trick. For example,
while(scanf("%d %d %d", &var1, &var2 & var3) == 3) {
// Statements here
}
So my question is there any such features available in java's Scanner.hasNextInt or Scanner.hasNext("regex").
I have also tried sc.hasNext("[0-9]* [0-9]* [0-9]*") but didn't worked actually.
Thank you in advance.
hasNext(regex) tests only single token. Problem is that default delimiter is one-or-more-whitespaces so number number number can't be single token (delimiter - space - can't be part of it). So sc.hasNext("[0-9]* [0-9]* [0-9]*") each time will end up testing only single number. BTW in your pattern * should probably be + since each number should have at least one digit.
To let spaces be part of token we need to remove them from delimiter pattern. In other words we need to replace delimiter pattern with one which represents only line separators like \R (more info). This way if user will write data in one line (will use enter only after third number) that line would be seen as single token and can be tested by regex.
Later you will need to set delimiter back to one-or-more-whitespaces (\s+) because nextInt also works based on single token, so without it we would end up with trying to parse string like "1 2 3".
Scanner sc = new Scanner(System.in);
sc.useDelimiter("\\R");
System.out.print("Write 3 numbers (sepate them with space): ");
while(!sc.hasNext("\\d+ \\d+ \\d+")){
String line = sc.nextLine();//IMPORTANT! Consume incorrect values
System.out.println("This are not 3 numbers: "+line);
System.out.print("Try again: ");
}
//here we are sure that there are 3 numbers
sc.useDelimiter("\\s+");//nextInt can't properly parse "num num num", we need to set whitespaces as delimiter
int var1 = sc.nextInt();
int var2 = sc.nextInt();
int var3 = sc.nextInt();
System.out.println("var1=" + var1);
System.out.println("var2=" + var2);
System.out.println("var3=" + var3);
Possible problem with this solution is fact that \d+ will let user provide number of any length, which may be out of int range. If you want to accept only int take a look at Regex for a valid 32-bit signed integer. You can also use nextLong instead, since long has larger range, but still it has max value. To accept any integer, regardless of its length you can use nextBigInteger().
I tried with nextLine method and usage of Pattern. Regex is matching with 3 numbers which is separeted with space. So it can be like this i think ;
Scanner scanner = new Scanner(System.in);
Pattern p = Pattern.compile("[0-9]+\\s[0-9]+\\s[0-9]+$");
while(!p.matcher(scanner.nextLine()).find()){
System.out.println("Please write a 3 numbers which is separete with space");
}
System.out.println("Yes i got 3 numbers!");
I hope this helps you.

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 :)

Java Scanner while loop

I'm trying to take in a string input which consists of multiple lines of numbers separated by ',' and ';' .
Example:
1,2;3,4;5,6;
9,8;7,6;
0,1;
;
Code:
ArrayList<Integer> alist = new ArrayList<>();
String delims = ";|\\,";
int i = 0;
Scanner input = new Scanner(System.in);
input.useDelimiter(delims);
while (input.hasNext()) {
alist.add(i, input.nextInt());
System.out.print(i + ' ');
System.out.print(alist.get(i) + '\n');
i++;
}
System.out.print('x');
When I run this in eclipse:
1,2;3,4;5,6; ( <= what i typed in console)
321133123413351436153716 ( <= output)
I'd expect something more like:
0 1
1 2
2 3
3 4
4 5
5 6
x
Why am I getting this sort of output?
One problem is that System.in is basically an infinite stream: hasNext will always return true unless the user enters a special command that closes it.
So you need to have the user enter something that tells you they are done. For example:
while(input.hasNext()) {
System.out.print("Enter an integer or 'end' to finish: ");
String next = input.next();
if("end".equalsIgnoreCase(next)) {
break;
}
int theInt = Integer.parseInt(next);
...
For your program, you might have the input you are trying to parse end with a special character like 1,2;3,4;5,6;end or 1,2;3,4;5,6;# that you check for.
And on these lines:
System.out.print(i + ' ');
System.out.print(alist.get(i) + '\n');
It looks like you are trying to perform String concatenation but since char is a numerical type, it performs addition instead. That is why you get the crazy output. So you need to use String instead of char:
System.out.print(i + " ");
System.out.print(alist.get(i) + "\n");
Or just:
System.out.println(i + " " + alist.get(i));
Edit for comment.
You could, for example, pull the input using nextLine from a Scanner with a default delimiter, then create a second Scanner to scan the line:
Scanner sysIn = new Scanner(System.in);
while(sysIn.hasNextLine()) {
String nextLine = sysIn.nextLine();
if(nextLine.isEmpty()) {
break;
}
Scanner lineIn = new Scanner(nextLine);
lineIn.useDelimiter(";|\\,");
while(lineIn.hasNextInt()) {
int nextInt = lineIn.nextInt();
...
}
}
Since Radiodef has already answered your actual problem(" instead of '), here are a few pointers I think could be helpful for you(This is more of a comment than an answer, but too long for an actual comment):
When you use Scanner, try to match the hasNextX function call to the nextX call. I.e. in your case, use hasNextInt and nextInt. This makes it much less likely that you will get an exception on unexpected input, while also making it easy to end input by just typing another delimiter.
Scanners useDelimiter call returns the Scanner, so it can be chained, as part of the initialisation of the Scanner. I.e. you can just write:
Scanner input = new Scanner(System.in).useDelimiter(";|\\,");
When you add to the end of an ArrayList, you don't need to(and usually should not) specify the index.
int i = 0, i++ is the textbook example of a for loop. Just because your test statement doesn't involve i does not mean you should not use a for loop.
Your code, with the above points addressed becomes as follows:
ArrayList<Integer> alist = new ArrayList<>();
Scanner input = new Scanner(System.in).useDelimiter(";|\\,");
for (int i = 0; input.hasNextInt(); i++) {
alist.add(input.nextInt());
System.out.println(i + " " + alist.get(i));
}
System.out.println('x');
Edit: Just had to mention one of my favorite delimiters for Scanner, since it is so suitable here:
Scanner input = new Scanner(System.in).useDelimiter("\\D");
This will make a Scanner over just numbers, splitting on anything that is not a number. Combined with hasNextInt it also ends input on the first blank line when reading from terminal input.

Categories