-3

SOLUTION Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods

First the code: This part works fine: (pr(String s) <==> System.out.println(s))

pr("Stage:");
                String stage = sc.next();
                Stage st;
                try{
                    st = Stage.valueOf(stage);
                }
                catch(IllegalArgumentException e){
                    inv();//Println "Invalid Input!"
                    break;
                }

end then:

pr("End:");
            String en = sc.nextLine();
            LocalDateTime end;
            try
            {
                int d = Integer.parseInt(en.substring(0,2));
                int m = Integer.parseInt(en.substring(3, 5));
                int h = Integer.parseInt(en.substring(7, 9));
                int min = Integer.parseInt(en.substring(10));
                 end = LocalDateTime.of(year, m, d, h, min);
            }
            catch ( NumberFormatException f)
            {
                inv();//Prints Invalid Input!
                break;
            }

I get an

java.lang.StringIndexOutOfBoundsException: String index out of range: 2
at java.lang.String.substring(Unknown Source)

When debugging the scanner is always skipping the "End" input.

EDIT en is "" but the input seems to be an infinite loop (e.g: 12.11. 13:14 \n \n \n ...) Therefore I cant save my input in en

EDIT2 Input is always "MM.dd. HH:mm" else print"Invalid Input"

How do I get rid of this problem? Is it caused by println?

Community
  • 1
  • 1
C-3ow
  • 61
  • 2
  • 9
  • 2
    Print the value of the `en` String , it is probably shorter than 3 characters . – Arnaud Feb 19 '16 at 13:20
  • Actually the length of `en` would have to be at least 11 for the code _not_ to break. The format would have to be something like `\d{2}.\d{2}..\d{2}.\d+`. – Thomas Feb 19 '16 at 13:25

1 Answers1

0

The problem is: nextInt() ignores the "\n" character, therefore nextline() reads the rest of the line "\n".

Details: Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods

Community
  • 1
  • 1
C-3ow
  • 61
  • 2
  • 9