how to read int,double,and sentence of string using same scanner variable

Gokul Raj picture Gokul Raj · Oct 5, 2015 · Viewed 48.6k times · Source
import java.util.Scanner;

public class Solution {

    public static void main(String[] args) {
            Scanner sc=new Scanner(System.in);
            String s=new String();
            int x=sc.nextInt();
            double y=sc.nextDouble();
            s = sc.next();

            System.out.println("String:"+s);
            System.out.println("Double: "+y); 
            System.out.println("Int: "+x);     
     }       
}

it scans only one word pleasd give any suggestions...

Answer

Puneet Soni picture Puneet Soni · Dec 4, 2017

You can try this code:

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

    scan.nextLine();
    String s = scan.nextLine();

    System.out.println("String: " + s);
    System.out.println("Double: " + d);
    System.out.println("Int: " + i);
}

Because the Scanner object will read the rest of the line where its previous read left off.

If there is nothing on the line, it simply consumes the newline and moves to the starting of the next line.

After double declaration, you have to write: scan.nextLine();