-4

I'm still new in java, I want to set while loop for int year such as the year is not equal to any input string. How should i do?

This is my code:

int year = input.nextInt();

while (year < 1400 || year > 2600) {
    System.out.println("Invalid year, please enter again: ");
    year = input.nextInt();
}

enter image description here

Federico klez Culloca
  • 22,898
  • 15
  • 55
  • 90
Caesar
  • 1
  • 1
  • 1
    You have to catch the exception. See [here](https://stackoverflow.com/a/3572233/133203) on how to handle it. – Federico klez Culloca Dec 14 '20 at 11:47
  • Use `nextLine()` to read the input. Then attempt to parse it `Integer.parseInt(...)`. Try-catch the `NumberFormatException`. Break out of the loop if no exception, continue if it happens. – Zabuzard Dec 14 '20 at 11:49

2 Answers2

0

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
Deepak Tatyaji Ahire
  • 3,469
  • 2
  • 6
  • 22
-1

The user input should match the int input type. Use a try-catch block to avoid exceptions when entering String inputs.

try{
    while (year < 1400 || year > 2600) {
      System.out.println("Invalid year, please enter again: ");
      year = input.nextInt();
    }
}
catch(Exception e){
    e.printStackTrace();
}
Thiluxan
  • 73
  • 7