KnowledgeBoat Logo
|

Computer Applications

Give the output of the following program segment:

void encode() 
{ 
    String s= "DICe"; 
    char ch; 
    for(i=0;i<4;i++) 
    {  ch=s.charAt(i); 
        if("AEIOUaeiou".indexOf(ch)>=0) 
        System.out.println("@"); 
else 
System.out.println(ch); 
}   

Java String Handling

1 Like

Answer

The given code snippet is missing the closing curly brace } for the method encode().

The corrected code is as follows:

void encode() 
{ 
    String s= "DICe"; 
    char ch; 
    for(i=0;i<4;i++) 
    {  ch=s.charAt(i); 
        if("AEIOUaeiou".indexOf(ch)>=0) 
        System.out.println("@"); 
else 
System.out.println(ch); 
}  
}
Output
D
@
C
@
Explanation

1. void encode() — Declares a method named encode that does not return any value (void).

2. String s = "DICe"; — Inside the method, a String variable s is initialized with the value "DICe".

3. char ch; — Declares a variable ch of type char which will be used to store each character of the string during the loop.

4. for(i=0;i<4;i++) — Starts a for loop where the integer variable i begins at 0.

  • The loop continues as long as i is less than 4.
  • After each iteration, i is incremented by 1.

5. ch = s.charAt(i); — Inside the loop, the character at position i in the string s is extracted using charAt(i) and stored in the variable ch.

6. if("AEIOUaeiou".indexOf(ch) >= 0) — This if statement checks whether the character ch is a vowel.

  • The string "AEIOUaeiou" contains all uppercase and lowercase vowels.
  • The method indexOf(ch) returns the position of ch in this string if found; otherwise, it returns -1.
  • If the return value is 0 or greater (meaning ch is found in the string), the condition evaluates to true.

7. System.out.println("@"); — If the condition is true (i.e., ch is a vowel), this line prints the symbol "@". 8. System.out.println(ch); — If the character is not a vowel, the original character ch is printed.

Answered By

3 Likes


Related Questions