Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to input a sentence in Java

Tags:

java

The code I have written takes as input just a single string and not a whole sentence and I want a whole sentence to be taken as input:

import java.util.Scanner;

public class Solution {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int i; 
        i= scan.nextInt();
        double d;
        d=scan.nextDouble();
        String s;
        s=scan.next();
        System.out.println("String: " + s);
        System.out.println("Double: " + d);
        System.out.println("Int: " + i);
    }
}

The test case is "Welcome to Java" and it's just showing "Welcome" in the output. Everything else is working fine. Please help.

like image 688
Sarthak Rana Avatar asked Jun 25 '16 11:06

Sarthak Rana


People also ask

How do you input words in Java?

Ways to take string input in Java:Using BufferedReader class readLine() method. Using Scanner class nextLine() method. Through Scanner class next() method. Using Command-line arguments of the main() method.

What does input () do in Java?

The input is the data that we give to the program. The output is the data what we receive from the program in the form of result. Stream represents flow of data or the sequence of data. To give input we use the input stream and to give output we use the output stream.


1 Answers

you can try the following, it will work.

public static void main(String args[]) {    
        // Create a new scanner object
        Scanner scan = new Scanner(System.in); 

        // Scan the integer which is in the first line of the input
        int i = scan.nextInt(); 

        // Scan the double which is on the second line
        double d = scan.nextDouble(); 

        /* 
         * At this point, the scanner is still on the second line at the end
         * of the double, so we need to move the scanner to the next line
         * scans to the end of the previous line which contains the double. 
         */
        scan.nextLine();    

        // reads the complete next line which contains the string sentence            
        String s = scan.nextLine();    

        System.out.println("String: " + s);
        System.out.println("Double: " + d);
        System.out.println("Int: " + i);
  }
like image 120
Arafat Avatar answered Oct 01 '22 21:10

Arafat