The best way is to make use of Exception handling. Also, scan the input using nextLine() method and parse the using Integer.parseInt() method.
Make use of appropriate exception that is thrown when the string is invalid (NumberFormatException in this case).
Have a look at the following code:
import java.util.Scanner;
class Solution{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int yearInValidIntergerForm;
while (true) {
String year = input.nextLine();
try{
yearInValidIntergerForm = Integer.parseInt(year);
if(yearInValidIntergerForm<1400 || yearInValidIntergerForm>2600){
//Custom exception - this is optional. As an alternative, you can just print invalid message instead of throwing exception.
throw new Exception("Invalid range for input year.");
}
System.out.println("Success");
break;
}catch(NumberFormatException e){
System.out.println("Input is not a valid integer.");
}catch(Exception e){
System.out.println(e.getMessage());
}
}
}
}
Input:
bgsd
3400
1500
Output:
Input is not a valid integer.
Invalid range for input year.
Success