Code
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your year of birth:");
boolean hasNextInt = scanner.hasNextInt();
if(hasNextInt) {
int yearOfBirth = scanner.nextInt();
scanner.nextLine(); //Handles NewLine Key/character (Enter)
System.out.println("Enter your name: ");
String name = scanner.nextLine();
int age = 2018 - yearOfBirth;
if(age >= 0 && age <= 100) {
System.out.println("Your name is: " + name + " , and you are " + age + " years old.");
} else {
System.out.println("Invalid year of birth");
}
} else {
System.out.println("Unable to parse year of birth");
}
scanner.close();
}
}
I'm mostly confused about two parts.....
boolean hasNextInt = scanner.hasNextInt();
^Is that reading user input, and testing to see if it's an integer? if so, why do we see
int yearOfBirth = scanner.nextInt();
later? Isn't that redundant? Asking for user input of integer twice?