Click here to Skip to main content
15,894,180 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
C#
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;
        s = scan.nextLine();
        System.out.println("String: " + s);
        System.out.println("Double: " + d);
        System.out.println("Int: " + i);
    }
}


This is the code.
What changes should i make to the code inorder to accept a string with blank spaces as input and print it ?

What I have tried:

Input (stdin):
42
3.1415
Good Morning have a nice day!

My Output (stdout):
String:
Double: 3.1415
Int: 42

Expected Output:
String:Good Morning have a nice day!
Double: 3.1415
Int: 42
Posted
Updated 25-Sep-16 21:33pm
v3
Comments
Maciej Los 26-Sep-16 2:07am    
Seems that everything is OK.

Try this-
Java
//s = scan.nextLine();
Scanner scanner = new Scanner(s);


Hope, it helps :)
 
Share this answer
 
Ok. This is going to be a Question and Answer type. I found the answer for my question just now.

I have placed the nextLine method just after the nextInt/nextDouble method.

I forgot the fact that nextInt method wouldn't read the "/n" newline character that is given through stdin by user.

So before placing the nextLine method, a blank scan.nextLinemethod would read through the "/n" newline character.

Corrected code looks like this:
C#
scan.nextLine();
String s;
s = scan.nextLine();
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900