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

Write a Java class that obtains a String from the end user. Validate that it is

ID: 671008 • Letter: W

Question

Write a Java class that obtains a String from the end user. Validate that it is between 5 and 25 characters long. If it isn’t, display an error message. If it is, proceed and use the String class to generate the output below. The output will of course vary based on the value the user types in for the String.

Invalid length:

Type a string from 5 to 25 characters and press Enter: Hi

Error: length must be from 5 to 25 characters

Valid length:

Type a string from 5 to 25 characters and press Enter: MBachman@towson.edu

String length: 19
Uppercase: DVESNO1@TOWSON.EDU
Lowercase: dvesno1@towson.edu
Characters in the first five positions: dvesn
Character at the first position: D
Position of the @: 8
Last four characters: .edu

Explanation / Answer

import java.lang.*;
import java.util.*;

class StringManip
{
public static void main(String[] args)
{
   Scanner input = new Scanner(System.in);
   String str;
   int l;

   while(true)
   {
    System.out.print("Type a string from 5 to 25 characters and press Enter :");
    str = input.nextLine();
    l = str.length();
    if(l>=5 && l<=25)
      break;
    else
     System.out.println("Error: length must be from 5 to 25 characters");
   }
   System.out.println("String length : "+l);
   System.out.println("Uppercase : "+str.toUpperCase());
   System.out.println("Lowercase : "+str.toLowerCase());
   System.out.println("Characters in the first five positions : "+str.substring(0,5));
   System.out.println("Character at the first position : "+str.charAt(0));
   System.out.println("Position of the @ (-1 if @ does not occur in string) : "+(str.indexOf('@')+1));
   System.out.println("Last four characters : "+str.substring(str.length() - 4));
}
}

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