Answer:
import java.util.Scanner;
public class MyClass {
public static void validateString(String str){
if(str.length()!=4){
System.out.println("Invalid Length");
main(null);
}
System.out.println("Valid Length");
}
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.print("Input: ");
String str;
str = input.nextLine();
validateString(str);
}
}
Step-by-step explanation:
import java.util.Scanner;
public class MyClass {
The validateString(String str) method begine here
public static void validateString(String str){
This checks if length of string is exactly 4 characters
if(str.length()!=4){
If no, it prints invalid length and returns back to the main function
System.out.println("Invalid Length");
main(null);
}
If yes, this line will be executed
System.out.println("Valid Length");
}
The main method begins here
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
This prompts user for input
System.out.print("Input: ");
This declares str as string
String str;
This gets user input
str = input.nextLine();
This passes user input to the validateStr function
validateString(str);
}
}