30

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.*;

class 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);
    }
}
Quotidian
  • 35
  • 3
  • 10
Bonett09
  • 345
  • 1
  • 3
  • 3

23 Answers23

41

This approach is working, but I don't how, can anyone explain, how does it works..

String s = sc.next();
s += sc.nextLine();
  • 14
    Because method `nextLine()` reads next symbols from current current line after cursors current position. For example, if your input contains 2 line `1` and `Hello World`. And source like that: `int x = sc.nextInt(); String s = sc.nextLine()`. In this case, after `nextInt()`, the cursor stays after the symbol "1" and this is the end of this line and `nextLine()` reads nothing. But, when you write code as you wrote top, at first, cursor moves to the next line and reads the word "Hello". Then cursor stays right after the word "Hello". And the command `sc.nextLine()` reads next symbols -" World". – Ulphat Aug 12 '16 at 06:03
  • 4
    First time ever seen an answer, which itself a question got many upvotes – Ravi Oct 18 '17 at 14:57
  • 1
    The **next()** methods scan for tokens (you can think of this as a word) and the **nextLine()** methods read from the Scanner's current location until the beginning of the next line – Arun Mar 27 '18 at 08:49
  • Suppose inout is : "Hello World I am Java"; then String s = sc.next(); -> will return "Hello" .... Now, according to doc., nextLine() returns "the line that was skipped..." hence, s += sc.nextLine(); will be like -> Hello + World I am Java i.e. final string: "Hello World I am Java" – Prajwal Waingankar Jun 07 '20 at 14:14
16

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

Nomad
  • 177
  • 2
  • 4
12

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.

Anthony Forloney
  • 84,001
  • 14
  • 111
  • 112
6

Default delimiter of Scanner is whitespace. Check javadoc for how to change this.

Raghuram
  • 49,195
  • 9
  • 101
  • 120
5
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*/
Frits
  • 6,116
  • 10
  • 39
  • 50
Vinayak
  • 1
  • 1
  • 4
5

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: ");
Michael Borgwardt
  • 327,225
  • 74
  • 458
  • 699
5
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);

    }
}
Manoj kumar
  • 440
  • 4
  • 13
ayush sharma
  • 51
  • 1
  • 3
4

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

} }

Malsha
  • 41
  • 4
3

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 !

2
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);
    }
}
ρяσѕρєя K
  • 127,886
  • 50
  • 184
  • 206
2

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

Hulk
  • 5,295
  • 1
  • 25
  • 49
Gourab Konar
  • 150
  • 2
  • 13
2

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);
    }
}
Luciano van der Veekens
  • 5,586
  • 4
  • 21
  • 29
Asid
  • 31
  • 4
0

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

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;
}
Gubatron
  • 5,581
  • 5
  • 31
  • 35
0

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

Tom
  • 14,120
  • 16
  • 41
  • 47
0

"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"
magician
  • 377
  • 3
  • 7
0

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();
}
akshaya pandey
  • 827
  • 6
  • 15
0

java.util.Scanner; util - package, Scanner - Class

  1. next() reads the string before the space. it cannot read anything after it gets the first space.
  2. 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)

  1. My

  2. 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();
}
venkatskpi
  • 622
  • 6
  • 6
0

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

0
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!!")

-1

I had the same question. This should work for you:

s.nextLine();
Prasad Khode
  • 5,897
  • 11
  • 38
  • 52
-2

Use nextLine() instead of next() for taking sentence as string input.

Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
Abhijith S
  • 492
  • 3
  • 17
Akshay Suresh
  • 353
  • 3
  • 9
-4

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

    }
}
  • 1
    this answer is incorrect. If you test this code the lines with "s.nextLine();" will return nothing - an empty string. Dont use this answer! – Rubinum Nov 05 '14 at 08:33
  • @Rubinum This code here is not wrong (logically wrong, yes, but not technically) and if your code returned an empty String, then you failed to use `s.nextLine()` correctly. That's not user114573s fault. – Tom Oct 17 '17 at 03:32