1

I have a huge problem understanding the sequence of my code execution. My program has to take 10 integer inputs and calculate them. So, I used forloop to take 10 inputs. After getting few errors and playing with it around I finally made the code without bugs. But I quite don't understand how it works. The program is simple. Please take a look

public static void main(String[] args) {
        int count = 0; //initializing the total sum as 0
        Scanner scanner = new Scanner(System.in);
     
        for (int i=1; i<=10; i++){
     
            System.out.println("Enter "+i+"th value :");
            boolean hasNextInt = scanner.hasNextInt(); //to check if the input is integer
           
            if(hasNextInt) {
                int value = scanner.nextInt(); //taking input here. here is my doubt
                count += value;
            }
            else {
                System.out.println("   invalid value");
                i--;
            }
            scanner.nextLine();
        }
        System.out.println("The sum of the values are "+count);
        scanner.close();
    }

Now, the input is taken in line 11 in the given program. But the integer condition is checking in line 10. By line 10, it doesn't even have input at all. How can it check the input? The sequence doesn't make sense to me. Thank you for any explanation.

  • Does this answer your question? [Scanner is skipping nextLine() after using next() or nextFoo()?](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo) – PM 77-1 Sep 14 '20 at 15:29
  • No, I understand that newline concept but my problem is with the sequence of code which checks if the input is integer or string. Please read my description. – Naveen Kumar Sep 14 '20 at 15:45

0 Answers0