0

I am doing a very basic Java program :

import java.util.Scanner;

public class App {
    
    private static Scanner sc = new Scanner(System.in);

    public static void main(String[] args) {
        int nbrFloors = 0;
        int nbrColumns = 0;
        int nbrRows = 0;

        System.out.println("So you have a parking with " + Integer.toString(nbrFloors) + " floors " + Integer.toString(nbrColumns) + " columns and " + Integer.toString(nbrRows) + " rows");
        System.out.print("What's the name of your parking ? ");
        String parkName = sc.next(); //or sc.nextLine() ?
        System.out.print("How much should an hour of parking ? If you want your parking to be free please type in '0' : ");
        float intPrice = Float.parseFloat(sc.next());
        Parking parking = new Parking(nbrFloors, nbrColumns, nbrRows, parkName, intPrice);
        
    }
}

As you can see on line 16 I use the Scanner.next() method because using Scanner.nextLine() skips user input. However I learned in this thread Java Scanner why is nextLine() in my code being skipped? that when you use the Scanner.next() method it skips whatever is after the first word you entered.

So I wonder how you can ask for a user input, while both not skipping it (because Scanner.nextLine() does that) and reading the whole input ?

ScarySneer
  • 199
  • 3
  • 9

1 Answers1

0

Your code skips user input because nextLine() method reads a line up-to the newLine character (carriage return). So after nextLine() finishes the reading the carriage return actually stays in the input buffer. That's why when you call sc.next(), it immediately reads the carriage return from the input buffer and terminates the reading operation. What you need to do is implicitly clear the input buffer after a read-line operation. To do that, simply call sc.next() one time after line 16.

    System.out.print("What's the name of your parking ? ");
    String parkName = sc.nextLine();
    sc.next();
    System.out.print("How much should an hour of parking ? If you want your parking to be free please type in '0' : ");

Arun123
  • 118
  • 6
  • Oh thank you. Java / Scanner has a very strange behavior : why does it keep the carriage return in the input buffer ? – ScarySneer Jan 20 '21 at 20:32
  • it's just how the methods are designed. normally you denote the termination of a input string either by carriage return, or blank space or tab. so the methods treats these characters as termination characters and read upto they encounter these. similarly how when reading a file you read till EOF but don't actually read EOF itself. so it gets left behind. – Arun123 Jan 21 '21 at 05:08