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.
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.
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With