In Java language, Ask the user for a string. Display the length of the string an
ID: 3795582 • Letter: I
Question
In Java language, Ask the user for a string. Display the length of the string and the first 5 characters of the string. Of course, if the string does not have 5 characters, issue an error message. Display the string in upper case, lower case, and display the first and the last character of the string. Create a new string (display its value, too) that holds the first 2 characters of the string followed by the letter X, followed by the exclamation mark (!), followed by the last 3 characters of the string.
Explanation / Answer
Hi,
Please see below the java class and sample output. Pleasecomment for any queries/feedbacks.
Thanks,
Anita
StringCheck.java
import java.util.Scanner;
public class StringCheck {
public static void main(String [] args){
Scanner scan = new Scanner(System.in);
String stringInput = "";
//Asking the user to entera String
System.out.println("Please Enter a String : ");
stringInput = scan.nextLine();
//Displaying the length of the string entered
if(stringInput.length()<5){
System.out.println("Length of the string is less than 5!");
}
else{
System.out.println("Length : "+stringInput.length());
}
//UPPER CASE
System.out.println("Upper Case : "+stringInput.toUpperCase());
//Lower case
System.out.println("Lower Case : "+stringInput.toLowerCase());
//First and lastcharacter os the string
System.out.println("First Character : "+stringInput.charAt(0) + " Last Character : "+stringInput.charAt(stringInput.length()-1));
//Creating new String
String newString = "";
newString = newString +stringInput.substring(0,2); //getting the first 2 characters of stringInput
newString = newString+"X"+"!"; // appending X and ! to the newString
//getting the last 3 characters of the newString
//substring(index) Returns a string that is a substring of this string.
//The substring begins with the character at the specified index and extends to the end of this string.
newString = newString + stringInput.substring(stringInput.length()-3);
System.out.println("New String created : "+newString);
}
}
Sample Output:
Please Enter a String :
NECtaPhilIa
Length : 11
Upper Case : NECTAPHILIA
Lower Case : nectaphilia
First Character : N Last Character : a
New String created : NEX!lIa
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.