Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.*;  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);     } } 
like image 758
Bonett09 Avatar asked Oct 30 '10 13:10

Bonett09


People also ask

What is the difference between Scanner next () and Scanner nextLine ()?

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

Why does my Scanner nextLine skip?

Why is Scanner skipping nextLine() after use of other next functions? The nextLine() method of java. util. Scanner class advances this scanner past the current line and returns the input that was skipped.

What is the use of nextLine () method in Scanner class?

The nextLine() method of the java. util. Scanner class scans from the current position until it finds a line separator delimiter. The method returns the String from the current position to the end of the line.


2 Answers

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

String s = sc.next(); s += sc.nextLine(); 
like image 154
Arvind Ramachandran Avatar answered Sep 23 '22 08:09

Arvind Ramachandran


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

like image 45
Nomad Avatar answered Sep 21 '22 08:09

Nomad