-2

My example input: Welcome to Java

My output with this code: Welcome

Expected output: Welcome to java

What is wrong with the following code where it accepts multiple characters with spaces? If I use nextLine(), then I will not be allowed to input a string.

I figured it out. Thanks for the help.

import java.util.Scanner;
public class Example {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int i = scan.nextInt();
        double d = scan.nextDouble();
        //edited*******************
        String s = scan.nextLine();
        s = scan.nextLine();
        //*************************
        System.out.println("String: " + s);
        System.out.println("Double: " + d);
        System.out.println("Int: " + i);
    }
}
  • 3
    `scan.next();` -> `scan.nextLine();` Next time it'll be easier to check the Javadocs for the Scanner class: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#next() – Kon Jun 18 '16 at 19:25

1 Answers1

0

Calling scan.next() results in the program going until a space, etc is reached then it returns what it found. Using scan.nextLine() should do the trick.

Kyle J
  • 759
  • 6
  • 18