For avoiding any unwanted character which has been entered in console like \n
we use nextInt() or nextLine() etc.
But in these cases actually the control is going a step ahead leaving the unwanted string or something like this.
But I want to delete or flush out the memory of buffer in which other unwanted data is taken by the system.
For example -->
Scanner scan=new Scanner(System.in);
scan.nextInt();
scan.nextline();//this statement will be skipped
because the system is taking \n as a line next to the integer given as input.
In this case without using scan.nextLine() I want to simply clear/flush out the buffer memory where the \n was stored.
Now please tell me how to delete the input buffer memory in java
Thank you. :)
You can use this to clear all existing data in the buffer:
while(sc.hasNext()) {
sc.next();
}
If you are only doing this to remove the newline (\n) characters from the input, you can use:
while(sc.hasNext("\n")) {
sc.next();
}
If the goal is to only read integers and skip any other characters, this would work:
while(sc.hasNext() && !sc.hasNextInt()) {
sc.next();
}
you can simply use one more scan.nextLine() before taking the string as input.
Scanner scan = new Scanner(System.in);
int x = scan.nextInt();
scan.nextLine(); // clears the input buffer
String s = scan.nextLine(); // this statement won't get skip
Reference : the solution to this hackerrank question uses the same idea which I provided
Related
if I use a scanner to read system input, how do i store the input in one string?
So far I have something like this.
Scanner user_input = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = user_input.next();
If in the terminal I type, "Bob Saget", name = "Bob". I want name = "Bob Saget"
Can anyone give me detailed instructions, if they involve eliminating white space or using tokenizers or something?
Use nextLine instead of next in order to read the entire input line into your name variable :
String name = user_input.nextLine();
Use user_input.nextLine() method , it reads till ENTER key is pressed
Use the nextLine(); method. The next(); method only reads the first token, the input until the first space (separator).
nextLine();
reads the entire line.
am stuck with this question
6) Suppose you enter 34.3, the ENTER key, 57.8, the ENTER key, 789, the ENTER key. Analyze the following code.
Scanner scanner = new Scanner(System.in);
int value = scanner.nextDouble();
int doubleValue = scanner.nextInt();
String line = scanner.nextLine();
i know the answer, the line will be equal to '\n' when the last statement is executed but why?
can anyone please explain it for me please?
The Scanner reads as many tokens as necessary to get it's next output and then leaves all of the rest of the tokens there to be examined. nextInt() does not need the newline character so it leaves it in the token stream. When you call nextLine() it looks into the token stream, sees the newline character, and returns that.
Let's break this statement by statement.
Scanner scanner = new Scanner(System.in);
int value = scanner.nextDouble();
The system waits for you to type in the value.
34.3↲
The value is read as 34.3 but is truncated to 34 since it is stored as an integer. Now the next statement is executed.
int doubleValue = scanner.nextInt();
The system waits for you again to type in the value.
57.8↲
The value is read as 57 as you are using scanner.nextInt() and hence, the .8 is ignored. There is however a enter remaining in the buffer.
String line = scanner.nextLine();
The system now waits again for the input, and you type in this. The first new line is the remnant from the previous input.
↲
789↲
The scanner first sees the newline character, so it assumes that the line is terminated. So the value is read as \n
Hope this helps.
If I comment out the line garbage = scan.nextLine();, the while-loop runs infinitely. Otherwise, it does not. I understand why it will run infinitely if there were only the print command, but I don't completely understand how the inclusion of the garbage variable stops it from running infintely. Can someone explain please?
import java.util.Scanner;
public class TypeSafeReadInteger
{
public static void main(String [] args)
{
Scanner scan = new Scanner(System.in);
String garbage;
System.out.print("Enter age as an integer > ");
while (! scan.hasNextInt())
{
garbage = scan.nextLine();
System.out.print("\nPlease enter an integer > ");
}
int age = scan.nextInt();
System.out.println("Your age is " + age);
}
}
garbage is just a variable, what 'stops' the while loop is the nextLine() It is a method that waits for user input. The while doesn't continue until your user inputs something using a keyboard and saves the input into the garbage variable.
You need to know two things:
hasNextLine() does not advance the Scanner instance.
nextLine() does advance the Scanner instance.
By "advance the Scanner instance", I mean "consume" input. Think of input as a stream, and think of a scanner object as something that is consuming that stream.
Things in a normal stream can only be consumed once. You captured your's in a variable called garbage, but you could just as easily have called scan.nextLine() without storing the result. I strongly advise you to read the Javadoc on Scanner to see which methods advance the Scanner instance and which do not.
To fix your code:
while (!scan.hasNextInt())
{
scan.nextLine(); // the order of the lines inside the loop makes the difference!
System.out.print("\nPlease enter an integer > ");
// when you perform nextLine() here - you reach the beginning of the loop
// without a token in the scanner - so you end up looping forever
}
int age = scan.nextInt();
By the way - as you can see from the example above, garbage is redundant.
If the user inputs an integer, then everything works. If they don't, then you get the infinite loop without the garbage = scan.nextLine(); line due to the way the Scanner class works.
When you do something like scan.hasNextInt();, no characters are actually read from the input. So if a user input something like "cat" in response to your prompt, then the input would be paused just before the first letter of that word. Since you are looping until there is an integer in the input, nothing further is read and you will loop infinitely because "cat" is just sitting in the input buffer.
By adding in the scan.nextLine() you will cause the Scanner to discard everything up to when the user hit <enter> and additional input could be processed.
This is my code:
Scanner scan = new Scanner(System.in);
String speed_string = scan.nextLine();
String[] string_array = speed_string.split("\\s");
I want my code to handle newlines, such as copy-pasting two or more paragraphs into a single nextLine. Is that possible? As it is currently, it will take in whatever the input until the newline.
It will stop at the newline, as per the API states:
Since this method continues to search through the input looking for a
line separator, it may buffer all of the input searching for the line
to skip if no line separators are present
So no, you cannot paste a big block and expect it to take it at once.
See nextLine method
You can't change the fact that nextLine() returns one line. that's its whole purpose. You can read two lines and combine those two strings, though. Of course that means some knowledge of the file format.
There is no possibility to do that using Scanner class because it can only read line confirmed by 'enter' or newline sign.
But you can also handle concatenating two lines using ArrayUtils.
Scanner scan = new Scanner(System.in);
String speed_string = scan.nextLine();
String speed_string1 = scan.nextLine();
String[] string_array = speed_string.split("\\s");
String[] string_array1 = speed_string.split("\\s");
String[] both = ArrayUtils.addAll(string_array , string_array1 );
sry about my english :)
Im new to Java programming and i have a problem with Scanner. I need to read an Int, show some stuff and then read a string so i use sc.nextInt(); show my stuff showMenu(); and then try to read a string palabra=sc.nextLine();
Some one told me i need to use a sc.nextLine(); after sc.nextInt(); but i dont understand why do you have to do it :(
Here is my code:
public static void main(String[] args) {
// TODO code application logic here
Scanner sc = new Scanner(System.in);
int respuesta = 1;
showMenu();
respuesta = sc.nextInt();
sc.nextLine(); //Why is this line necessary for second scan to work?
switch (respuesta){
case 1:
System.out.println("=== Palindromo ===");
String palabra = sc.nextLine();
if (esPalindromo(palabra) == true)
System.out.println("Es Palindromo");
else
System.out.println("No es Palindromo");
break;
}
}
Ty so much for your time and Help :D
nextInt() only reads in until it's found the int and then stops.
You have to do nextLine() because the input stream still has a newline character and possibly other non-int data on the line. Calling nextLine() reads in whatever data is left, including the enter the user pressed between entering an int and entering a String.
When you input a value (whether String, int, double, etc...) and hit 'enter,' a new-line character (aka '\n') will be appended to the end of your input. So, if you're entering an int, sc.nextInt() will only read the integer entered and leave the '\n' behind in the buffer. So, the way to fix this is to add a sc.nextLine() that will read the leftover and throw it away. This is why you need to have that one line of code in your program.