178k views
5 votes
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.

User Olov
by
5.4k points

1 Answer

2 votes

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

}

}

User Tawnya
by
5.0k points