Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 218
Gokul Raj Avatar asked Oct 05 '15 12:10

Gokul Raj


People also ask

How do you input double in Scanner class?

The nextDouble() method of java. util. Scanner class scans the next token of the input as a Double. If the translation is successful, the scanner advances past the input that matched.

How do you read a string with a Scanner?

To read strings, we use nextLine(). To read a single character, we use next(). charAt(0). next() function returns the next token/word in the input as a string and charAt(0) function returns the first character in that string.


1 Answers

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

like image 193
Puneet Soni Avatar answered Oct 16 '22 22:10

Puneet Soni