How to enter a sentence in Java

The code I wrote takes only one line as input, not an entire sentence, and I want the whole sentence to be accepted 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 just displays a “Welcome” in the output. Everything else is working fine. Please help.

+10
java
source share
4 answers

you can use scan.nextLine(); to read the entire line.

+9
source share

You can try the following, this 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); } 
+2
source share

You must put scan.nextLine() after the above integer scan and double scan. Then use String s = scan.nextLine() . Like this,

 int i = scan.nextInt(); scan.nextLine(); double d = scan.nextDouble(); scan.nextLine(); String s = scan.nextLine(); 
0
source share
 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(); String s = scan.nextLine(); s = scan.nextLine(); System.out.println("String: " + s); System.out.println("Double: " + d); System.out.println("Int: " + i); } } 
-2
source share

All Articles