Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.company;
- import java.util.Scanner;
- /*
- Program reads User input year.
- Outputs year in proper format.
- */
- public class CurrentYear {
- public static void main(String[] args) {
- Scanner input = new Scanner(System.in);
- System.out.print("Input Valid Year): ");
- String year = input.nextLine();
- /*
- What if the user inputs a word or sentence?
- We need to return a pretty error message and not have the program stop without explaining the issue...
- */
- int x = 0;
- int yearInt = 0;
- try{ //tries code that may fail without stopping program.
- yearInt = Integer.parseInt(year);
- //Catches all NumberFormatExceptions but not other errors
- } catch(NumberFormatException e) {
- //Fix problem
- x = 1;
- }
- if(x == 1) // returns error message.
- {
- System.out.println("Input a number.");
- System.exit(2);
- }
- if(year.length() == 4)
- {
- //int yearInt = Integer.parseInt(year);
- System.out.print(yearInt);
- }
- if(year.length() == 2)
- {
- //int yearInt = Integer.parseInt(year);
- System.out.print(yearInt+2000);
- }
- if((year.length() != 4) && (year.length() != 2))
- {
- System.out.print("Year not valid.");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement