Solutions for Class 10 ICSE Logix Kips Computer Applications with BlueJ Java | IT Developer <?php echo $page_title; ?>
IT Developer

Conditional Constructs in Java

Chapter 9

Conditional Constructs in Java

Class 9 - Logix Kips ICSE Computer Applications with BlueJ


Share with a Friend

Java Programs - Program to display the colour of the spectrum (VIBGYOR) according to the user's choice using switch statement


import java.util.Scanner;

 

public class VIBGYOR {

    public static void main(String[] args) {

 

        Scanner sc = new Scanner(System.in);

 

        System.out.println("Choose a number (1-7) to display a colour:");

        System.out.println("1 - Violet");

        System.out.println("2 - Indigo");

        System.out.println("3 - Blue");

        System.out.println("4 - Green");

        System.out.println("5 - Yellow");

        System.out.println("6 - Orange");

        System.out.println("7 - Red");

 

        System.out.print("\nEnter your choice: ");

        int choice = sc.nextInt();

 

        switch (choice) {

            case 1:

                System.out.println("Colour: Violet");

                break;

            case 2:

                System.out.println("Colour: Indigo");

                break;

            case 3:

                System.out.println("Colour: Blue");

                break;

            case 4:

                System.out.println("Colour: Green");

                break;

            case 5:

                System.out.println("Colour: Yellow");

                break;

            case 6:

                System.out.println("Colour: Orange");

                break;

            case 7:

                System.out.println("Colour: Red");

                break;

            default:

                System.out.println("Invalid choice! Please select between 1 and 7.");

        }

 

        sc.close();

    }

}

Output

Output 1:

SAMPLE INPUT : Enter your choice: 3 SAMPLE OUTPUT : Colour: Blue

Output 2:

SAMPLE INPUT : Enter your choice: 7 SAMPLE OUTPUT : Colour: Red

Output 3: (Invalid Choice)

SAMPLE INPUT : Enter your choice: 9 SAMPLE OUTPUT : Invalid choice! Please select between 1 and 7.

Explanation

1. User Input

int choice = sc.nextInt();

  • Reads the user’s choice (1–7).
2. switch Statement

switch (choice)

  • Compares the value of choice with each case.
3. case Labels
  • Each case corresponds to one colour of the VIBGYOR spectrum.
4. break Statement
  • Prevents fall-through to the next case.
5. default Case
  • Executes when the user enters an invalid number.