Computer Applications

Define a class (using the Scanner class) to generate a pattern of a word in the form of a triangle or in the form of a­n inverted triangle, depending upon user's choice.

Sample Input:

Enter a word: CLASS  
Enter your choice: 1        
Sample Output:                
C
CL
CLA
CLAS
CLASS

Enter your choice: 2
Sample Output:
CLASS
CLAS
CLA
CL
C

Java

Java Library Classes

10 Likes

Answer

import java.util.Scanner;

public class KboatTriangleMenu
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter a word: ");
        String word = in.nextLine();
        System.out.println("Type 1 for a triangle");
        System.out.println("Type 2 for an inverted triangle");
        System.out.print("Enter your choice: ");
        int choice = in.nextInt();
        int len = word.length();
        
        switch (choice) {
            case 1:
                for(int i = 0; i < len; i++) {
                    for(int j = 0; j <= i; j++) {
                        System.out.print(word.charAt(j));
                    }
                    System.out.println();
                }
                break;
                
            case 2:
                for (int i = len - 1; i >= 0; i--) {
                    for (int j = 0; j <= i; j++) {
                        char ch = word.charAt(j);
                        System.out.print(ch);
                    }
                    System.out.println();
                }
                break;
                
            default:
                System.out.println("Incorrect choice");
                break;
        }
    }
}

Output

Answered By

5 Likes


Related Questions