Scanner doesn't read whole sentence - difference between next() and nextLine() of scanner class

Bonett09 picture Bonett09 · Oct 30, 2010 · Viewed 102.5k times · Source

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

Answer

Arvind Ramachandran picture Arvind Ramachandran · Feb 26, 2016

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

String s = sc.next();
s += sc.nextLine();