Scanner doesn't read whole sentence - difference between next() and nextLine() of scanner class
I'm writing a program which allows the user to input his data then outputs it. Its 3/4 correct but when it arrives at outputting the address it only prints a word lets say only 'Archbishop' from 'Archbishop Street'. How do I fix this?
import java.util.*;
cl开发者_StackOverflow社区ass MyStudentDetails{
public static void main (String args[]){
Scanner s = new Scanner(System.in);
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);
}
}
This approach should work:
String s = sc.next();
s += sc.nextLine();
Initialize the Scanner this way so that it delimits input using a new line character.
Scanner sc = new Scanner(System.in).useDelimiter("\\n");
Refer the JavaDoc for more details
Use sc.next() to get the whole line in a String
I would use Scanner#nextLine
opposed to next
for your address
attribute.
This method returns the rest of the current line, excluding any line separator at the end.
Since this returns the entire line, delimited by a line separator, it will allow the user to enter any address without any constraint.
String s="Hi";
String s1="";
//For Reading Line by hasNext() of scanner
while(scan.hasNext()){
s1 = scan.nextLine();
}
System.out.println(s+s1);
/*This Worked Fine for me for reading Entire Line using Scanner*/
Default delimiter of Scanner is whitespace. Check javadoc for how to change this.
Instead of using System.in
and System.out
directly, use the Console
class - it allows you to display a prompt and read an entire line (thereby fixing your problem) of input in one call:
String address = System.console().readLine("Enter your Address: ");
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String s = scan.next();
s += scan.nextLine();
System.out.println("String: " + s);
}
}
We can easily done using scan.nextLine .It will read the rest of the input till the end. Then assign it to your variable. Entire sentence can be printed easily . Here is the example for your better understanding.
String s = "HackerRank ";
Scanner scan = new Scanner(System.in);
String s2;
scan.nextLine(); // read the rest of the line of input (newline character after the double token).
s2 = scan.nextLine();
/* Concatenate and print the String variables on a new line integer variables on a new line;
System.out.println(s + s2);
scan.close();
} }
next()
will only store the input up to the first token. if there are two words "Hi there" it means there are two tokens separated by space (delimiter). Every time you call the next() method it reads only one token.
if input is "Hi there !"
Scanner scan = new Scanner(System.in);
String str = scan.next()
System.out.println(str);
Output
Hi
So if you both the words you need to call next()
again to get the next token which is inefficient for longer string input
nextLine()
on the other hand grabs the entire line that the user enters even with spaces
Scanner scan = new Scanner(System.in);
String str = scan.nextLine()
System.out.println(str);
Output
Hi there !
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
double d = scan.nextDouble();
String s="";
while(scan.hasNext())
{
s=scan.nextLine();
}
System.out.println("String: " +s);
System.out.println("Double: " + d);
System.out.println("Int: " + i);
}
}
I tried following code but this is not stopping as there is no break condition so it always waiting for input , may be you could add a condition for break
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
double d = scan.nextDouble();
String s="";
while(scan.hasNext())
{
s=scan.nextLine();
}
System.out.println("String: " +s);
System.out.println("Double: " + d);
System.out.println("Int: " + i);
}
}
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.
for reading the entire line you can use nextLine()
java.util.Scanner; util - package, Scanner - Class
next()
reads the string before the space. it cannot read anything after it gets the first space.nextLine()
reads the whole line. Read until the end of the line or "/n". Note: Not The Next line
(Example)
My mission in life is not merely to survive, but to thrive;
and to do so with some passion, some compassion, some humor.
(Output)
My
My mission in life is not merely to survive, but to thrive;
Tricks:
If you want to read the next line Check Java has
method.
while (scanner.hasNext()) {
scan.next();
}
while (scanner.hasNext()) {
scan.nextLine();
}
next() is read until the space of the encounter, and the nextLine() is read to the end of the line.
Scanner scan = new Scanner(System.in);
String address = scan.next();
s += scan.nextLine();
To get the whole adress add
s.nextLine();//read the rest of the line as input
before
System.out.println("Enter Your Address: ");
String address = s.next();
I set the token delimiter to be a newline pattern, read the next token, and then put the delimiter back to whatever it was.
public static String readLine(Scanner scanner) {
Pattern oldDelimiter = scanner.delimiter();
scanner.useDelimiter("\\r\\n|[\\n\\x0B\\x0C\\r\\u0085\\u2028\\u2029]");
String r = scanner.next();
scanner.useDelimiter(oldDelimiter);
return r;
}
"it only prints a word lets say only 'Archbishop' from 'Archbishop Street"
It is only printing the word because Scanner functions such as next(), nextInt(), etc. read only a token at time. Thus this function reads and returns the next token.
For example if you have: x y z
s.next() will return x
s.nextLine() y z
Going back to your code if you want to read the whole line "Archbishop Street"
String address = s.next(); // s = "Archbishop"
Then address += s.nextLine(); // s = s + " Street"
Below is the sample code to read a line in Standard input using Java Scanner class.
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
System.out.println(s);
scan.close();
}
}
Input:
Hello World
Output:
Hello World
the below piece of code should do what yoiu are looking for:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
System.out.println(s);
scan.close();
}
Scanner scanner = new Scanner(System.in);
String str = scanner.next();
str += scanner.readLine();
String str = scanner.next(); ===> it fetch the 1st word of the line (hello world!! => "hello") str += scanner.nextLine(); ===> This method returns the rest of the current line, excluding any line separator at the end. (hello world!! => " world!!")
Try this !!!
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
s = scan.nextLine();
scan.close();
System.out.println("String: " + s);
}
I had the same question. This should work for you:
s.nextLine();
Use nextLine()
instead of next()
for taking sentence as string input.
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
You can do this:
class MyStudentDetails{
public static void main (String args[]){
Scanner s = new Scanner(System.in);
System.out.println("Enter Your Name: ");
String name = s.nextLine();
System.out.println("Enter Your Age: ");
String age = s.nextLine();
System.out.println("Enter Your E-mail: ");
String email = s.nextLine();
System.out.println("Enter Your Address: ");
String address = s.nextLine();
System.out.println("Name: "+name);
System.out.println("Age: "+age);
System.out.println("E-mail: "+email);
System.out.println("Address: "+address);
}
}
精彩评论