Problem: Read in a word and display the requested characters from that word in the requested format. Write a Java program that
● prompts the user for a word and reads it,
● converts all characters of the input word to upper case and displays every character whose index is a multiple of 3 starting from the 1st one,
● next converts all characters of the input word to lower case and displays the word with the characters in reverse order,
● finally displays the original word as it was entered by the user.
Based on the previous specifications your program should behave and look exactly as shown in the cases below. Your program should work for any word entered by the user, not just the ones
in the samples. Below illustrates how your program should behave and appear.
Example output: Enter◦a◦word:◦elephant↵
↵
EPN↵
tnahpele↵
elephant
Enter◦a◦word:◦Nancy12A↵
↵
NC2↵
a21ycnan↵
Nancy12A
The program is given below. The comments are provided for the better understanding of the logic.
import java.util.Scanner;
public class StringOperations{
public static void main(String[] args) {
//Initialse the scanner object.
Scanner sc = new Scanner(System.in);
//Display a message on the screen to enter a word.
System.out.print("Enter a word: ");
//Get the word from the command line.
String word = sc.nextLine();
//Convert the word to upper case and store it in a variable wordUpper
String wordUpper = word.toUpperCase();
//Loop from 0 to number of characters in the word-1.
for (int i = 0; i < wordUpper.length(); i++) {
//Check of the index is divisible by 3.
//i % 3 will return 0 if a number is divisible by 3.
if(i % 3 == 0) {
//Extract that character and print it, if the number is divisible by 3.
char c = wordUpper.charAt(i);
System.out.print(c);
}
}
//Print a blank line.
System.out.println("");
String wordReversed = "";
//Loop in the reverse order from number of characters in the word-1 to 0
for (int i = word.length() - 1; i > -1; i--) {
//Extract the character and append it to the variable wordReversed
char c = word.charAt(i);
wordReversed = wordReversed + c;
}
//At the end of the above loop the variable wordReversed will have the reversed word.
//Also convert the reversed word to lowercase.
wordReversed = wordReversed.toLowerCase();
System.out.println(wordReversed);
//Print the original word.
System.out.println(word);
}
}
The screenshots of the code and output are provided below.
Get Answers For Free
Most questions answered within 1 hours.