0

I'm trying to get Scanner to read input in the following format:

0, 0
1, 1
2, 2
3, 3

And putting each pair into a queue. However, It's skipping over the first and second to last line. this is my code:

    Scanner input = new Scanner(System.in);
    System.out.println("Enter values: ");

    while (input.hasNextLine() && !input.nextLine().equals("-1")) {
        System.out.println(jobs.peek());
        String str = input.nextLine();
        int aT = Integer.parseInt(String.valueOf(str.charAt(0))); // this is the first number
        int sT = Integer.parseInt(String.valueOf(str.charAt(3))); // this is the second number after the space
    }
    input.close();

I know the problem has to do with the !input.nextLine().equals("-1") part of my while loop condition since it doesn't skip anything when I remove it. But if I do that I get an index out of bound exception when it tries to read the last empty line (which is why I'm trying to use -1 as a sentinel). What am I doing wrong?

Alex
  • 63
  • 4
  • 2
    Of course it's skipping input. You're getting input and discarding it in the while condition `!input.nextLine()`. Don't do that. Put the input into a String and test it and then use it. – Hovercraft Full Of Eels Apr 03 '18 at 00:43
  • I see. But why is this a problem? Am I not saying "Do this while you have a next line and that line does not contain the value -1"? @HovercraftFullOfEels – Alex Apr 03 '18 at 00:47
  • Why is it a problem? -- you're seeing the problem yourself first hand. You're getting the input, testing it in the while condition but discarding it. Again you need to store it into a variable if you want to *both* use it in the test and do something else with it. Think logically what your code is doing -- walk through your code on paper, a skill that you will need moving forward. – Hovercraft Full Of Eels Apr 03 '18 at 00:48
  • @HovercraftFullOfEels Got it, thank you. – Alex Apr 03 '18 at 00:52

0 Answers0