Ali Mustafa
Ali Mustafa

Reputation: 565

Why is this program not running correctly?

I have the following code:

import java.util.Scanner;

public class Practice {
public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    //System.out.println("Enter quantity:");
    //int quantity = input.nextInt();
    //System.out.println("You entered: " + quantity);

    //System.out.println("Enter price: ");
    //double price = input.nextDouble();
    //System.out.println("You entered: " + price);

    System.out.println("Enter city: ");
    String city = input.nextLine();
    System.out.println("You entered: " + city);
    System.out.println("Enter state code: ");
    String state = input.next();
    System.out.println("You entered: " + state);
}

}

When I run the program with the middle section commented out like this, it works correctly. But when I uncomment it, it messes up the last block by printing the following lines simultaneously:

Enter city: 
You entered: 
Enter state code: 

Why is this happening, and how can I fix it?

Upvotes: 0

Views: 70

Answers (3)

chettri
chettri

Reputation: 11

use ScnObj.next() instead of ScnObj.nextLine();

System.out.println("Enter price: ");
double price = ScnObj.nextDouble();
System.out.println("You entered: " + price);

System.out.println("Enter city: ");
String city = ScnObj.next();
System.out.println("You entered: " + city);

System.out.println("Enter state code: ");
String state = ScnObj.next();
System.out.println("You entered: " + state);

Upvotes: 0

You typed something like this:

12<enter>1.3<enter>AZ

right?

When you call nextInt, it reads the next integer. So it reads "12" and what is left is:

<enter>1.3<enter>AZ<enter>

Now you call nextDouble. It skips past the first <enter> and reads "1.3" (a double). What is left is:

<enter>AZ<enter>

Now you call nextLine, which reads until the next <enter>. Oh look, you already pressed <enter>! So it reads the <enter> and returns a blank line. What is left is:

AZ<enter>

Now you call nextLine again, which reads until the next <enter>. It reads AZ<enter> and returns "AZ".

This is a quirk of how Scanners and streams work. The usual fix is to call nextLine immediately after nextInt and nextDouble, and ignore the result. Something like:

System.out.println("Enter quantity: ");
int quantity = input.nextInt();
input.nextLine(); // ignore newline
System.out.println("You entered: " + quantity);

System.out.println("Enter price: ");
double price = input.nextDouble();
input.nextLine(); // ignore newline
System.out.println("You entered: " + price);

Upvotes: 1

EDToaster
EDToaster

Reputation: 3180

input.nextDouble();

does not consume the line, insert a line:input.nextLine(); right after the commented block, don't assign it to any variable.

Upvotes: 0

Related Questions