Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not getting the expected output in Java

Input Format

  • The first line contains an integer, .
  • The second line contains a double, .
  • The third line contains a string, .

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!
like image 843
Ketan G Avatar asked Dec 07 '25 13:12

Ketan G


2 Answers

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();
like image 126
Jon Skeet Avatar answered Dec 09 '25 02:12

Jon Skeet


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();
like image 24
Naruto Avatar answered Dec 09 '25 02:12

Naruto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!