0

I have trouble using the nextLine() method from the java Scanner class.

I need to read a whole line from the console, with spaces, and I cannot do that because the previous reading of an int/string is somehow affecting the reading of the line and I get an empty string.

I can read just one string with next() but I need the spaces between...

here is a chunk of the code:

        String[] parametri = new String[7];

        System.out.println("Izberite vrsto transakcije:\n 1.Dobavnica \n 2.Izdajnica\n");
        parametri[0] = String.valueOf(scan.nextInt());

        System.out.print("Korisnik (id): ");
        parametri[2] = String.valueOf(scan.nextInt());
        //!!! here is the error
        System.out.print("Korisnik (ime): ");
        parametri[3] = scan.nextLine();
        //!!! and here
        System.out.print("Artikel: ");
        parametri[4] = scan.nextLine();

        System.out.print("Enota količine: ");
        parametri[5] = scan.next();

        System.out.print("Količina: ");
        parametri[6] = String.valueOf(scan.nextInt());

The output is in slovenian, it's a transaction parameters input

Mark
  • 253
  • 1
  • 5
  • 22
  • possible duplicate of [Scanner issue when using nextLine after nextXXX](http://stackoverflow.com/questions/7056749/scanner-issue-when-using-nextline-after-nextxxx) – Denis Tulskiy Mar 23 '14 at 16:32

1 Answers1

3

After call to nextInt() there is still a caret return character ('\n') in input buffer. You need to remove it using scanner.skip("[\r\n]+")

Denis Tulskiy
  • 19,012
  • 6
  • 50
  • 68