Consider you have already created a validateString(String str) method that validates a String to ensure it contains exactly 4 characters. Create code that calls this method, sending user input as an argument (actual parameter). The user should be continuously prompted to enter a different string and informed of an error if the method returns false.

Respuesta :

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);

}

}

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);

}

}

Q&A Education