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

java (15 points) Write a program that reads a line of input as a string and prin

ID: 3726521 • Letter: J

Question

java (15 points)
Write a program that reads a line of input as a string and prints
a. Only the uppercase letters in the string.
b. Every second letter of the string.
c. The string, with all vowels replaced by an underscore.
d. The number of vowels in the string.
e. The positions of all vowels in the string.
Instructions:
4) The main method should present a menu for selecting the choice a,b,c,d, or e
5) Write one method for each option above
6) Display the output in the method itself
7) Use String methods from Common Loop Algorithms

Explanation / Answer

import java.util.Scanner;

public class JavaProgram {

   public static void main(String[] args) {

       Scanner sc = new Scanner(System.in);

       System.out.print("Enter a string: ");

       String str = sc.nextLine();

       // printing only Upper case

       for(int i=0; i<str.length(); i++) {

           char c = str.charAt(i);

           if(c >= 'A' && c <='Z')

               System.out.print(c);

       }

       System.out.println();

       // printing every second letter

       for(int i=1; i<str.length(); i= i+2) {

           System.out.print(str.charAt(i));

       }

       System.out.println();

       // printing The string, with all vowels replaced by an underscore

       for(int i=0; i<str.length(); i++) {

           char c = str.charAt(i);

           if(Character.isLetter(c))

               c = Character.toLowerCase(c);

           if(c=='a'||c=='e'||c=='i'||c=='o'||c=='u')

               System.out.print("_");

           else

               System.out.print(c);

       }

       System.out.println();

       // printing number of vowels

       int count = 0;

       for(int i=0; i<str.length(); i++) {

           char c = str.charAt(i);

           if(Character.isLetter(c))

               c = Character.toLowerCase(c);

           if(c=='a'||c=='e'||c=='i'||c=='o'||c=='u')

               count++;

       }

       System.out.println("Number of vowels: "+count);

       // position of vowels in the string

       for(int i=0; i<str.length(); i++) {

           char c = str.charAt(i);

           if(Character.isLetter(c))

               c = Character.toLowerCase(c);

           if(c=='a'||c=='e'||c=='i'||c=='o'||c=='u')

               System.out.print(i+" ");

       }

       System.out.println();

   }

}

/*

Sample run:

Enter a string: This is My String

TMS

hsi ySrn

th_s _s my str_ng

Number of vowels: 3

2 5 14

*/