Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Java: please make sure it compiles. Write a program that takes a String as input

ID: 3890566 • Letter: J

Question

Java: please make sure it compiles.

Write a program that takes a String as input from the keyboard, representing a year. Your program should do the following:

utilize matches method to check if the input consists only of digits; if not give an error

for the valid input:
use switch statement on the length of the input

if the entered year has two characters, convert it to an int, add 2000 to it, and output it. Integer.parseIntmethod should be used to convert the input to its numeric representation

if the year entered has four characters just output it

if the year entered has neither two nor four characters (default case), output that the year is not valid

Explanation / Answer

YearTest.java

import java.util.Scanner;

public class YearTest {

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);

System.out.println("Enter the year: ");

String year = scan.next();

String regex = "[0-9]+";

if(year.matches(regex)) {

switch(year.length()) {

case 2: System.out.println((2000 + Integer.parseInt(year))); break;

case 4: System.out.println(year); break;

default: System.out.println("Entered year is not valid");

}

} else {

System.out.println("Invalid Input. Input must be all digits.");

}

}

}

Output:

Enter the year:
ab345
Invalid Input. Input must be all digits.

Enter the year:
22
2022

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote