0

I've been trying this program. But I'm not getting the required output.

import java.util.*;

class MiscTest {

    public static void main(String[] args) {

        int i = 10;
        double d = 4.0;
        String s = "Lavante ";

        Scanner scanner = new Scanner(System.in);

        int j;
        double dd;
        String ss;

        j = scanner.nextInt();
        dd = scanner.nextDouble();
        ss = scanner.next();

        System.out.println("\n" + (i + j));
        System.out.println(d + dd);
        System.out.println(s.concat(ss));

    }
}

The input I've given:

Input

The Output I got:

Output

I need the whole sentence "Lavante is from Maserati" as output. But, I'm getting only one word from the Second String. Help me. Thanks in advance.

4 Answers4

3

You need to use nextLine() otherwise, Scanner stops at the whitespace delimiter using next()

Also, after having used scanner.nextDouble(), use scanner.next() to consume the rest of the characters not read by the previous call, just like below.

dd = scanner.nextDouble();
scanner.next();
ss = scanner.nextLine();
Yassin Hajaj
  • 20,020
  • 9
  • 41
  • 81
3

Scanner#next() reads up to the first whitespace. If you want to read up to the end of the line, you should use nextLine() instead:

ss = scanner.nextLine();
Mureinik
  • 252,575
  • 45
  • 248
  • 283
1

You are currently using the next() Function which is using to take only a String before white spaces

Suppose Input : Hello World Then If User using next()

Output: Hello

To take the string till the End of line Use nextLine()

Input: Hello World If user using nextLine() Output: Hello World

Tushar Pal
  • 463
  • 6
  • 16
1

I guess you are hitting enter button after providing input of double variable. try code snippet.

dd = scan.nextDouble();
ss = scan.nextLine().trim();
if (ss.isEmpty()) {
   ss = scan.nextLine();
}
Govinda Sakhare
  • 3,317
  • 4
  • 22
  • 51