When I run this program, it doesn't work. I can enter your name, my birth year, the current year but after I enter the current year it doesn't display my age. Could you tell me what's wrong in my code and explain me why ? It seems like I didn't understand how input works in Java.
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner get_input = new Scanner(System.in);
System.out.println("Enter your name ");
String name = get_input.nextLine();
boolean is_int = false;
int year_of_birth = 0;
System.out.println("Enter your year of birth");
while (!get_input.hasNextInt()) {
System.out.println("Year invalid");
System.out.println("Enter your year of birth");
get_input.next();
}
year_of_birth = get_input.nextInt();
System.out.println("Enter the current year");
get_input.next();
int current_year=get_input.nextInt();
int age = current_year-year_of_birth;
System.out.println(current_year);
System.out.println(year_of_birth);
System.out.println("Your name is " + name + " and you are " + age + " year old.");
get_input.close();
}
}
Thanks in advance
If you remove the get_input.next(); after printing the "Enter the current year" your problem should go away. I would also add error checking in that area because the user can enter an invalid year.