Ketan G
Ketan G

Reputation: 517

Not getting the expected output in Java

Input Format

Output Format

Print the sum of both integers on the first line, the sum of both doubles (scaled to decimal place) on the second line, and then the two concatenated strings on the third line.Here is my code

package programs;

import java.util.Scanner;


public class Solution1 {

    public static void main(String[] args) {
        int i = 4;
        double d = 4.0;
        String s = "Programs ";

        Scanner scan = new Scanner(System.in);
        int i1 = scan.nextInt();
        double d1 = scan.nextDouble();
        String s1 = scan.next();

        int i2 = i + i1;
        double d2 = d + d1;
        String s2 = s + s1;
        System.out.println(i2);
        System.out.println(d2);
        System.out.println(s2);
        scan.close();
    }
}

Input (stdin)

12
4.0
are the best way to learn and practice coding!

Your Output (stdout)

16
8.0
programs are

Expected Output

16
8.0
programs are the best place to learn and practice coding!

Upvotes: 3

Views: 198

Answers (4)

Jon Skeet
Jon Skeet

Reputation: 1499860

Scanner.next() reads the next token. By default, whitespace is used as a delimited between tokens, so you're only getting the first word of your input.

It sounds like you want to read a whole line, so use Scanner.nextLine(). You need to call nextLine() once to consume the line break after the double though, as per this question.

// Consume the line break after the call to nextDouble()
scan.nextLine();
// Now read the next line
String s1 = scan.nextLine();

Upvotes: 3

Farhan Yaseen
Farhan Yaseen

Reputation: 2677

You need to use scan.nextLine() which will read a complete line and scan.next() read value each with space as delimiter.

package programs;

import java.util.Scanner;


public class Solution1 {

    public static void main(String[] args) {
        int i = 4;
        double d = 4.0;
        String s = "Programs ";

        Scanner scan = new Scanner(System.in);
        int i1 = scan.nextInt();
        double d1 = scan.nextDouble();
        String s1 = scan.nextLine();

        int i2 = i + i1;
        double d2 = d + d1;
        String s2 = s + s1;
        System.out.println(i2);
        System.out.println(d2);
        System.out.println(s2);
        scan.close();
    }
}

Upvotes: 1

jarvo69
jarvo69

Reputation: 8339

All you need to do is change

String s1 = scan.next();

to

    String s1 = scan.nextLine();

Upvotes: 1

Naruto
Naruto

Reputation: 4329

You are using scan.next() which reads value each with space as delimiter.

But here you need to read complete line so use

String s1 = scan.nextLine();

Upvotes: 3

Related Questions