Does anybody know how i could make scanner ignore space? I wanna type a first and second name, but scanner wont let me, i want to save the full name
String name;
System.out.print("Enter name: ");
name = scan.next(); //Ex: John Smith
System.out.println(name);
Edit:
New problem.. While using nextLine in my extended program, nextLine just ignores the whole question and moves on without a chance to scan the name.
Scanner#next() splits lines around whitespace. Scanner.nextLine() does not, therefore leaving spaces in.
name = scan.nextLine(); //Ex: John Smith
Well, first your System.out.print(); call is flawed. Everything inside must be inside quotations
System.out.print("Enter name: ");
scan.next() gets the next character in the stream, whereas scan.nextLine() gets the next line (terminated by an EOL character), which may be more helpful to you.
After that, you can create an array of words, like
String[] broken = name.split(" ");
which will place into broken all of the words that you've typed in delimited by spaces.
Then you can go something like
for(int i = 0; i < broken.size; i++)
{
System.out.print(broken[i] + " ");
}
System.out.println();
Scanner.next delimits using whitespaces, to read a full line you can use:
name = scan.nextLine();
use scanner.nextLine() which reads full line, instead of scan.next();
Example:
name = scan.nextLine();
Read oracle documentation for Scanner class for available methods.
sounds like you want to read the entire line (minus the line ending). if someone enters, "helen r. smith", you can read the line in with:
name = scan.nextLine();
YOU CAN DO LIKE THIS
import java.util.*;
class scanner2
{
public static void main(String args[])
{
Scanner in= new Scanner(System.in);
System.out.println("enter the name");
String name= in.nextLine();//for name with spaces with more than one word or for one word.
System.out.println("enter single word");
String rl= in.next();//single word name
System.out.println("name is "+name+" rl is "+rl);
}
}
Execute it you will get your answer.
Related
I'm trying to create a videoStore with the basic CRUD operation. For creating each movie I need to read the title, the year and the gender as below:
System.out.print("name: ");
name = in.nextLine();
System.out.print("year: ");
year = in.nextInt();
in.nextLine();
System.out.print("gender: ");
gender = in.next();
When I enter the addMovie option, I get this print on the console
(name: year:)
Can someone explain to me why it happens as above?
Here is the rest of the method:
static ArrayList<Movie> movies = new ArrayList<Movie>();
static Scanner in = new Scanner(System.in);
public static void InserirFilme() {
String name;
int year;
String gender;
boolean existe = false;
System.out.print("name: ");
name = in.nextLine();
System.out.print("year: ");
year = in.nextInt();
in.nextLine();
System.out.print("gender: ");
gender = in.next();
Movie movie = new Movie(name, year, gender);
for(Movie m: movies)
{
if(movie == m)
{
existe = true;
}
}
if(!existe)
{
movies.add(movie);
}
else
{
System.out.println("the movie already exists in the videoStore");
}
}
Calling next does not remove the line break, which means the next time you call InserirFilme the call to read the name can complete immediately. Use nextLine.
System.out.print("gender: ");
gender = in.nextLine();
(You probably mean "genre" instead of "gender" though)
Also, as mentioned in the comments, this check will never succeed:
if(movie == f)
You run this method in loop (right?)
The first call reads input correctly, but it leaves the linebreak in System.in after the last in.next().
On next call the name: is printed, then scanner reads an empty string from System.in because the linebreak already exists here.
And after thet the year: is printed on the same line because no new linebreaks are entered.
So you just have to insert another in.nextLine() after reading gender (or genre :) )
Or use nextLine() for read genre instead of next(), because genre might have more than one word.
But there are some disadvantages with using fake nextLine() to 'eat' linebreak - there might be another text which you doesn't process. It's a bad practice - to loose the data user entered.
It is better to read all the data from line, then validate/parse it, check isn't there some extra data, and if the data is invalid show notification and let him try to enter the right value.
Here are some examples how to deal with user input manually - https://stackoverflow.com/a/3059367/1916536. This is helpful to teach yourself.
Try to generalize user input operations:
name = validatedReader.readPhrase("name: ");
year = validatedReader.readNumber("year: ");
genre = validatedReader.readWord("genre: ");
where ValidatedReader is a custom wrapper for Scanner which could use your own validation rules, and could gently re-ask user after a wrong input.
It could also validate dates, phone numbers, emails, url's or so
For production purposes, it is better to use validation frameworks with configurable validation rules. There are a lot of validation frameworks for different purposes - Web, UI, REST etc...
when i enter the addMovie option, i get this print on the console (name: year:) can someone explain me why it happens i already searched a lot and i cant understand why :S
The way i understood your question is that you are getting the output (name: year: ) in a line and want it in seperate lines? In that case you simply can use System.out.println(String); instead of System.out.print(String). On the other hand you can also use "\n" whenever you want a linebreak within a String. Hope i could help you :).
Edit: If this was not an answer to your question, feel free to tell me and clarify your question :)
For String name you are using in.nextLine(); i.e the data entered on the entire line will be added to name string.
After "name: " is displayed, enter some text and press enter key, so that the year and gender fields will get correct values.
The code written is correct but you are not giving appropriate input through the scanner.
I recommend to use
String name = in.next();//instead of String name = in.nextLine();
You may instantiate Scanner Class differently for String and Integer type input. It works for me :)
Example:
static Scanner in1 = new Scanner(System.in);
static Scanner in2 = new Scanner(System.in);
Please use nextLine() for 'name' and 'gender'. It may contain more than one word. Let me know if it works.
Example:
System.out.print("name: ");
name = in1.nextLine();
System.out.print("year: ");
year = in2.nextInt();
System.out.print("gender: ");
gender = in1.nextLine();
I'm using two scanners, 1 for reading in the whole file and the 2nd one for reading in the current line.
The input coming in from the file would be in the format string,int,string.
The issue is that if the 3rd string has a space it will only read in the part of the string up to the white space, and on the next loop the scanner grabs the 2nd part of the 1st string.
So for example if the 3rd string would be "the tree", word only becomes " the", and type will become " tree", which messes up the whole program. So all I need it to do, is make the 3rd string become the rest of the line because I already got the required information.
while(scanner.hasNextLine()) {
String line = reader.next();
line = line.replaceAll("," , " ");
Scanner scan = new Scanner(line);
String type = scan.next();
int quant = scan.nextInt();
String word = scan.nextLine();
scan.close();
}
Edit: Solved it myself, line should be reader.nextLine() not reader.next().
What is the main difference between next() and nextLine()?
My main goal is to read the all text using a Scanner which may be "connected" to any source (file for example).
Which one should I choose and why?
I always prefer to read input using nextLine() and then parse the string.
Using next() will only return what comes before the delimiter (defaults to whitespace). nextLine() automatically moves the scanner down after returning the current line.
A useful tool for parsing data from nextLine() would be str.split("\\s+").
String data = scanner.nextLine();
String[] pieces = data.split("\\s+");
// Parse the pieces
For more information regarding the Scanner class or String class refer to the following links.
Scanner: http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
String: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
next() can read the input only till the space. It can't read two words separated by a 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.
For reading the entire line you can use nextLine().
From JavaDoc:
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
next(): Finds and returns the next complete token from this scanner.
nextLine(): Advances this scanner past the current line and returns the input that was skipped.
So in case of "small example<eol>text" next() should return "small" and nextLine() should return "small example"
The key point is to find where the method will stop and where the cursor will be after calling the methods.
All methods will read information which does not include whitespace between the cursor position and the next default delimiters(whitespace, tab, \n--created by pressing Enter). The cursor stops before the delimiters except for nextLine(), which reads information (including whitespace created by delimiters) between the cursor position and \n, and the cursor stops behind \n.
For example, consider the following illustration:
|23_24_25_26_27\n
| -> the current cursor position
_ -> whitespace
stream -> Bold (the information got by the calling method)
See what happens when you call these methods:
nextInt()
read 23|_24_25_26_27\n
nextDouble()
read 23_24|_25_26_27\n
next()
read 23_24_25|_26_27\n
nextLine()
read 23_24_25_26_27\n|
After this, the method should be called depending on your requirement.
What I have noticed apart from next() scans only upto space where as nextLine() scans the entire line is that next waits till it gets a complete token where as nextLine() does not wait for complete token, when ever '\n' is obtained(i.e when you press enter key) the scanner cursor moves to the next line and returns the previous line skipped. It does not check for the whether you have given complete input or not, even it will take an empty string where as next() does not take empty string
public class ScannerTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int cases = sc.nextInt();
String []str = new String[cases];
for(int i=0;i<cases;i++){
str[i]=sc.next();
}
}
}
Try this program by changing the next() and nextLine() in for loop, go on pressing '\n' that is enter key without any input, you can find that using nextLine() method it terminates after pressing given number of cases where as next() doesnot terminate untill you provide and input to it for the given number of cases.
next() and nextLine() methods are associated with Scanner and is used for getting String inputs. Their differences are...
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.
import java.util.Scanner;
public class temp
{
public static void main(String arg[])
{
Scanner sc=new Scanner(System.in);
System.out.println("enter string for c");
String c=sc.next();
System.out.println("c is "+c);
System.out.println("enter string for d");
String d=sc.next();
System.out.println("d is "+d);
}
}
Output:
enter string for c
abc def
c is abc
enter string for d
d is def
If you use nextLine() instead of next() then
Output:
enter string for c
ABC DEF
c is ABC DEF
enter string for d
GHI
d is GHI
In short: if you are inputting a string array of length t, then Scanner#nextLine() expects t lines, each entry in the string array is differentiated from the other by enter key.And Scanner#next() will keep taking inputs till you press enter but stores string(word) inside the array, which is separated by whitespace.
Lets have a look at following snippet of code
Scanner in = new Scanner(System.in);
int t = in.nextInt();
String[] s = new String[t];
for (int i = 0; i < t; i++) {
s[i] = in.next();
}
when I run above snippet of code in my IDE (lets say for string length 2),it does not matter whether I enter my string as
Input as :- abcd abcd or
Input as :-
abcd
abcd
Output will be like
abcd
abcd
But if in same code we replace next() method by nextLine()
Scanner in = new Scanner(System.in);
int t = in.nextInt();
String[] s = new String[t];
for (int i = 0; i < t; i++) {
s[i] = in.nextLine();
}
Then if you enter input on prompt as -
abcd abcd
Output is :-
abcd abcd
and if you enter the input on prompt as
abcd (and if you press enter to enter next abcd in another line, the input prompt will just exit and you will get the output)
Output is:-
abcd
From javadocs
next() Returns the next token if it matches the pattern constructed from the specified string.
nextLine() Advances this scanner past the current line and returns the input that was skipped.
Which one you choose depends which suits your needs best. If it were me reading a whole file I would go for nextLine until I had all the file.
From the documentation for Scanner:
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
From the documentation for next():
A complete token is preceded and followed by input that matches the delimiter pattern.
Just for another example of Scanner.next() and nextLine() is that like below :
nextLine() does not let user type while next() makes Scanner wait and read the input.
Scanner sc = new Scanner(System.in);
do {
System.out.println("The values on dice are :");
for(int i = 0; i < n; i++) {
System.out.println(ran.nextInt(6) + 1);
}
System.out.println("Continue : yes or no");
} while(sc.next().equals("yes"));
// while(sc.nextLine().equals("yes"));
Both functions are used to move to the next Scanner token.
The difference lies in how the scanner token is generated
next() generates scanner tokens using delimiter as White Space
nextLine() generates scanner tokens using delimiter as '\n' (i.e Enter
key presses)
A scanner breaks its input into tokens using a delimiter pattern, which is by default known the Whitespaces.
Next() uses to read a single word and when it gets a white space,it stops reading and the cursor back to its original position.
NextLine() while this one reads a whole word even when it meets a whitespace.the cursor stops when it finished reading and cursor backs to the end of the line.
so u don't need to use a delimeter when you want to read a full word as a sentence.you just need to use NextLine().
public static void main(String[] args) {
// TODO code application logic here
String str;
Scanner input = new Scanner( System.in );
str=input.nextLine();
System.out.println(str);
}
I also got a problem concerning a delimiter.
the question was all about inputs of
enter your name.
enter your age.
enter your email.
enter your address.
The problem
I finished successfully with name, age, and email.
When I came up with the address of two words having a whitespace (Harnet street) I just got the first one "harnet".
The solution
I used the delimiter for my scanner and went out successful.
Example
public static void main (String args[]){
//Initialize the Scanner this way so that it delimits input using a new line character.
Scanner s = new Scanner(System.in).useDelimiter("\n");
System.out.println("Enter Your Name: ");
String name = s.next();
System.out.println("Enter Your Age: ");
int age = s.nextInt();
System.out.println("Enter Your E-mail: ");
String email = s.next();
System.out.println("Enter Your Address: ");
String address = s.next();
System.out.println("Name: "+name);
System.out.println("Age: "+age);
System.out.println("E-mail: "+email);
System.out.println("Address: "+address);
}
The basic difference is next() is used for gettting the input till the delimiter is encountered(By default it is whitespace,but you can also change it) and return the token which you have entered.The cursor then remains on the Same line.Whereas in nextLine() it scans the input till we hit enter button and return the whole thing and places the cursor in the next line.
**
Scanner sc=new Scanner(System.in);
String s[]=new String[2];
for(int i=0;i<2;i++){
s[i]=sc.next();
}
for(int j=0;j<2;j++)
{
System.out.println("The string at position "+j+ " is "+s[j]);
}
**
Try running this code by giving Input as "Hello World".The scanner reads the input till 'o' and then a delimiter occurs.so s[0] will be "Hello" and cursor will be pointing to the next position after delimiter(that is 'W' in our case),and when s[1] is read it scans the "World" and return it to s[1] as the next complete token(by definition of Scanner).If we use nextLine() instead,it will read the "Hello World" fully and also more till we hit the enter button and store it in s[0].
We may give another string also by using nextLine(). I recommend you to try using this example and more and ask for any clarification.
The difference can be very clear with the code below and its output.
public static void main(String[] args) {
List<String> arrayList = new ArrayList<>();
List<String> arrayList2 = new ArrayList<>();
Scanner input = new Scanner(System.in);
String product = input.next();
while(!product.equalsIgnoreCase("q")) {
arrayList.add(product);
product = input.next();
}
System.out.println("You wrote the following products \n");
for (String naam : arrayList) {
System.out.println(naam);
}
product = input.nextLine();
System.out.println("Enter a product");
while (!product.equalsIgnoreCase("q")) {
arrayList2.add(product);
System.out.println("Enter a product");
product = input.nextLine();
}
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println("You wrote the following products \n");
for (String naam : arrayList2) {
System.out.println(naam);
}
}
Output:
Enter a product
aaa aaa
Enter a product
Enter a product
bb
Enter a product
ccc cccc ccccc
Enter a product
Enter a product
Enter a product
q
You wrote the following products
aaa
aaa
bb
ccc
cccc
ccccc
Enter a product
Enter a product
aaaa aaaa aaaa
Enter a product
bb
Enter a product
q
You wrote the following products
aaaa aaaa aaaa
bb
Quite clear that the default delimiter space is adding the products separated by space to the list when next is used, so each time space separated strings are entered on a line, they are different strings.
With nextLine, space has no significance and the whole line is one string.
What actually happens here ?
Why can't I store a String with spaces in between as name ?
I tried the delimiter thing, but didn't worked. Is there a way that will produce the desired output ?
I know .next() works but we might need to store a string with space. Just curious ...
Scanner input=new Scanner(System.in);
System.out.print("Enter number of Students:");
double [] scores = new double[input.nextInt()];
String [] names=new String[scores.length];
for(int i=0;i<names.length;i++){
System.out.println("Enter the students name: ");
names[i] = input.nextLine();
System.out.println("Enter the student scores : ");
scores[i]=input.nextDouble();
}
when you call input.nextInt(), it doesn't consume the new line character on that line, so the following call to input.nextLine(); will consume the newline, and return the empty string. nextDouble() will function properly.
one way to fix this is to call input.nextLine(); immediately before the for loop to consume the extra new line character
Edit:
String [] names=new String[scores.length];
input.nextLine(); //literally add the call right here
for(int i=0;i<names.length;i++){
According to the Javadoc:
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.
What if you replace the default delimiter with "\n" like this:
Scanner s = new Scanner(input).useDelimiter("\\\\n");
This is how it works ! Thanks for concern guys! :)
for(int i=0;i<names.length;i++){
if(input.nextLine().equals("")){
System.out.println("Enter students name : ");
names[i] = input.nextLine();
}
System.out.println("Enter the student scores : ");
scores[i]=input.nextDouble();
}
Would anyone point me in the right direction, of why when i use a for loop the println function comes up two times in the output. Thanks
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number of employees to calculate:");
int numberEmployees = scan.nextInt();
for(int i=0; i<numberEmployees; i++){
System.out.println("Enter First Name:");
name = scan.nextLine();
System.out.println("Enter Last Name:");
last = scan.nextLine();
System.out.println("Enter Document #:");
document = scan.nextInt();
System.out.println("Enter Basic Salary");
basicSalary = scan.nextInt();
System.out.println("Enter # of Hours");
hours = scan.nextInt();
}
}
OUTPUT
Enter the number of employees to calculate:
1
Enter First Name:
Enter Last Name:
daniel
Enter Document #:
The problem is that when you entered 1 with a new line, the nextInt() function doesn't remove the newline that you had from entering in the 1. Change your calls to scan.nextInt() to Integer.parseInt(scan.nextLine()) and it should behave the way you want.
To further explain; here's stuff from the Java API.
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.
and
The next() and hasNext() methods and their primitive-type companion
methods (such as nextInt() and hasNextInt()) first skip any input that
matches the delimiter pattern, and then attempt to return the next
token. Both hasNext and next methods may block waiting for further
input.
So, what evidently happens (I didn't see anything on the page to confirm it) is that after next(), hasNext(), and their related methods read in a token, they immediately return it without gobbling up delimiters (in our case, whitespace) after it. Thus, after it read in your 1, the newline was still there, and so the following call to nextLine() had a newline to gobble and did so.
It appears that the newline character remains in your input after the first entry. When the next input is requested, the Scanner sees a newline character and interprets it as the end of the input. This makes it appear to skip every other input request. I would suggest checking out the Java API docs as to the exact behavior of Scanner's methods.