0

Very new to programming. I know this question will be very easy to answer for experienced programmers. I would like to continue running this program which finds leap years until the user enter "n." The program terminates before being able to enter y/n. Help is very much appreciated... thank you.

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        String another = "y";
        Scanner scan = new Scanner(System.in);
        System.out.print("Please enter a year ");
        int year = scan.nextInt();

        while (another.equals("y")) {

            if (year < 1582) {
                System.out.println("Not an established Gregorian year.");
            } else if (year % 4 != 0 || (year % 100 == 0 && year % 400 != 0)) {
                System.out.println("Not a leap year");
            } else {
                System.out.println("Leap year!");
            }

            System.out.println();
            System.out.print("Test another year (y/n)?");
            another = scan.nextLine();
        }
    }
}
Pshemo
  • 113,402
  • 22
  • 170
  • 242
garserdt216
  • 163
  • 6
  • 3
    So what exactly is the question? – Mureinik Jan 09 '16 at 23:38
  • 1
    edited to reflect the issue more clearly – garserdt216 Jan 09 '16 at 23:40
  • 2
    Your scan.nextInt() expression consumed the int from the keyboard, but left the \n behind. So, when the scan.nextLine() call is executed, it gets an empty string (which is not equal to "y"). Hence your loop exits. There is also a second problem that needs fixing. The scan.nextInt() call needs to be inside the loop, not outside. – LIProf Jan 09 '16 at 23:44
  • This is very common problem with Scanner. You need to remember that `nextWhatever()` will not consume line separator. Only `nextLine()` does it which means that for data like `123\n` scanners cursor (lets represent it with `|`) after calling `nextInt()` will be set `123|\n` right before line separator. Because of that `nextLine` which tries to read text until line separator will think that data provided by user which should represent line is empty. So your `another = scan.nextLine();` will store empty String `""` which is not equal to `y` and your loop exits. – Pshemo Jan 09 '16 at 23:46
  • @LIProf scan.nextInt() does belong in the loop. Thanks – garserdt216 Jan 09 '16 at 23:53

1 Answers1

0

The enter from when the person enters the year number at the beginning is not used up. It is stored in the "buffer" and when the program reaches the point where you ask if they want to do another year, it reads the enter that is in the buffer. To fix this you just need another scan.nextLine(); before the important one.

njasi
  • 126
  • 8