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.
Related
I have an assignment to create a program that will take input and print it to the console. Pretty simple. There is one issue though. I have to store the information in separate variables but the input looks like this.
Input:
Blah 123 Green
I'm aware that I can create a single scanner input tied to a single variable that will store all of that as one String but for the assignment Blah, 123, and Green would all have to be stored in different variables. Normally what I would do if I could use the enter key to signal new input would be
Scanner scan = new Scanner(System.in);
String first = scan.nextLine();
int second = Integer.parseInt(scan.nextLine());
String third = scan.nextLine();
but in this case, the spaces have to act as the enter key instead. how would I go about this?
You could use next() to read individual inputs:
String first = scan.next();
int second = scan.nextInt());
String third = scan.next();
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
I am trying to write a string input to a text file using the Scanner object.
The string input is a film name. If the file name has two words, though, the scanner object only takes the first word.
I need it to take both words. Here is my code:-
Scanner new_dvd_info = new Scanner(System.in);
System.out.println("Enter name of new film");`
String film_name = new_dvd_info.next();
Can anybody shed any light please?
Replace new_dvd_info.next() with new_dvd_info.nextLine() to grab the entire line.
Documentation of Scanner.next() method says
Finds and returns the next complete token from this scanner.
A complete token is preceded and followed by input that matches
the delimiter pattern. This method may block while waiting for input
to scan, even if a previous invocation of {#link #hasNext} returned
<code>true</code>.
So it would just pick up until it finds " " as delimiter in your case. You could use next line method on scanner to get whole string new_dvd_info.nextLine() alternatively you could just loop over like:
while(scanner.hasNext) {
//append to string using scanner.next();
}
The problem here is that you are using new_dvd_info.next() which returns the first complete token. If any delimiter such as space is encountered it considers the next word as a separate token.
Scanner sc=new Scanner(System.in);
String s=sc.next();
System.out.println(s);
In the above code if you give the name of the movie as Age of Ultron it will return you just the tokenAge as there is a delimiter after the token age.
In case you want the complete String separated by delimiter you should use
Scanner sc=new Scanner(System.in);
String s=sc.nextLine();
System.out.println(s);
This will give you the desired output i.e. Age of Ultron
I am writing a program that asks for the person's full name and then takes that input and reverses it (i.e John Doe - Doe, John). I started by trying to just get the input, but it is only getting the first name.
Here is my code:
public static void processName(Scanner scanner) {
System.out.print("Please enter your full name: ");
String name = scanner.next();
System.out.print(name);
}
Change to String name = scanner.nextLine(); instead of String name = scanner.next();
See more on documentation here - next() and nextLine()
Try replacing your code
String name = scanner.nextLine();
instead
String name = scanner.next();
next() can read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same line after reading the input.
nextLine() reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.
From Scanner documentation:
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
and
public String next()
Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern.
This means by default the delimiter pattern is "whitespace". This splits your text at the space. Use nextLine() to get the whole line.
public static void processName(Scanner scanner) {
System.out.print("Please enter your full name: ");
scanner.nextLine();
String name = scanner.nextLine();
System.out.print(name);
}
Try the above code Scanner should be able to read space and move to the next reference of the String
scanner.next(); takes only the next word. scanner.nextLine(); should work. Hope this helps
In case you do not want to use .nextLine() you can also configure .next() to use \n as the delimiter pattern using .useDelimiter() method like so:
public static void processName(Scanner scanner) {
System.out.print("Please enter your full name: ");
scanner.useDelimiter("\n");
String name = scanner.next();
System.out.print(name);
}
try using this
String name = scanner.nextLine();
In my current program one method asks the user to enter the description of a product as a String input. However, when I later attempt to print out this information, only the first word of the String shows. What could be the cause of this? My method is as follows:
void setDescription(Product aProduct) {
Scanner input = new Scanner(System.in);
System.out.print("Describe the product: ");
String productDescription = input.next();
aProduct.description = productDescription;
}
So if the user input is "Sparkling soda with orange flavor", the System.out.print will only yield "Sparkling".
Any help will be greatly appreciated!
Replace next() with nextLine():
String productDescription = input.nextLine();
Use input.nextLine(); instead of input.next();
The javadocs for Scanner answer your question
A Scanner breaks its input into tokens using a delimiter pattern,
which by default matches whitespace.
You might change the default whitespace pattern the Scanner is using by doing something like
Scanner s = new Scanner();
s.useDelimiter("\n");
input.next() takes in the first whitsepace-delimited word of the input string. So by design it does what you've described. Try input.nextLine().
Javadoc to the rescue :
A Scanner breaks its input into tokens using a delimiter pattern,
which by default matches whitespace
nextLine is probably the method you should use.