Advertisement
sudoaptinstallname

Untitled

Jan 17th, 2019
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.42 KB | None | 0 0
  1. package com.company;
  2.  
  3. import java.util.Scanner;
  4.  
  5. /*
  6. Program reads User input year.
  7. Outputs year in proper format.
  8. */
  9.  
  10. public class CurrentYear {
  11. public static void main(String[] args) {
  12. Scanner input = new Scanner(System.in);
  13.  
  14. System.out.print("Input Valid Year): ");
  15.  
  16. String year = input.nextLine();
  17. /*
  18. What if the user inputs a word or sentence?
  19. We need to return a pretty error message and not have the program stop without explaining the issue...
  20. */
  21. int x = 0;
  22. int yearInt = 0;
  23. try{ //tries code that may fail without stopping program.
  24. yearInt = Integer.parseInt(year);
  25. //Catches all NumberFormatExceptions but not other errors
  26. } catch(NumberFormatException e) {
  27. //Fix problem
  28. x = 1;
  29. }
  30. if(x == 1) // returns error message.
  31. {
  32. System.out.println("Input a number.");
  33. System.exit(2);
  34. }
  35.  
  36. if(year.length() == 4)
  37. {
  38. //int yearInt = Integer.parseInt(year);
  39. System.out.print(yearInt);
  40. }
  41. if(year.length() == 2)
  42. {
  43. //int yearInt = Integer.parseInt(year);
  44. System.out.print(yearInt+2000);
  45. }
  46. if((year.length() != 4) && (year.length() != 2))
  47. {
  48. System.out.print("Year not valid.");
  49. }
  50.  
  51.  
  52. }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement