My program terminates before letting me enter an answer
I am writing a program that reads a year from the keyboard and says if it is a leap year or not. After it tells you, it asks if you want to check another year, however the program terminates before accepting an answer.
This is the program:
//-----------------------------------
//Programmer: Zach Powers
//Date: 9/21/2011
//This program does alot, read PP5.2 on page 286 of Java Software Solutions for more info.
//----------------------------------------------------------------/
import java.util.Scanner;
public class PP5_2
{
public static void main(String[] args)
{
int year;
String answer;
Scanner scan = new Scanner(System.in);
System.out.println("Would you like to check a year (y/n)?");
answer = scan.nextLine();
while (answer.equalsIgnoreCase("y"))
{
System.out.println("Enter a year: ");
year = scan.nextInt();
if (year >= 1582)
{
if (year%4 == 0)
{
if (year%100 == 0)
{
if (year%400 == 0)
{
System.out.println("That year is a leap year.");
}
else
{
System.out.println("That year is not a leap year.");
}
}
else
{
System.out.println("That year is a leap year");
}
}
else
{
System.out.println("That year is not a leap year");
}
}
else
{
System.out.println("That year was before leap years existed!");
}
System.out.println();
System.out.print ("Would you like to check another year? (y/n)");
answer = scan.nextLine();
}
}
}
And this is the output I receive:
----jGRASP exec: java PP5_2
Would you like to check a year (y/n)?
y
Enter a year:
2000
That year is a leap year.
Would you like to check another year? (y/n)
----jGRASP: operation complete.
Re: My program terminates before letting me enter an answer
When you type something into the console and hit enter it consists of what you type and the enter key even though you don't see it. So if you type "1996" and hit enter what really got input was "1996/n". When you read an integer using nextInt() it leaves behind that newline sequence (/n) because it only reads in integers. Now when you call nextLine() it reads in that newline sequence that was left behind and since it's not equal to "y" the program exits. To solve this you have to call nextLine() after the call to nextInt() to get rid of the newline sequence. Something like this:
Code:
year = scan.nextInt();
scan.nextLine();
Just so you know, the Advanced Java section is meant for more advanced problems. This thread should probably be in the New to Java section. Also when posting code it's best to use the [code][/code] tags so that your code stays formatted and is easier to read. Just paste your code in between those tags.
Re: My program terminates before letting me enter an answer
Moved from "Advanced Java"
Please post beginner questions in this section.
db