User Tools

Site Tools


Sidebar

Programming Reference/Librarys

Question & Answer

Q&A is closed







java:control_structures:switch

switch

The switch statement is a multi-select control structure. An expression is evaluated once and compared to 'constants'. In case of equality, the 'statements' that come after the 'constant' are processed. In switch 'statements' can only ordinary data types (ie, 'int', 'long', char, short, etc.) can be used.

switch(expression)
{
   case constant1:
       statements
   break;
 
   case constant2:
       statements
   break;
 
   case constantn:
       statements
   break;
 
   default:
       statements
}

example of switch in java

package schoolnotes;
import java.util.Scanner;
 
public class Schoolnotes{
 
 
    public static void main(String[] args) {
 
        int note;
        Scanner scan = new Scanner(System.in);
 
        System.out.print("Please enter a note: ");
        note = scan.nextInt();
 
        switch(note) {
 
            case 1: System.out.println("very well");
                break;
            case 2: System.out.println("good");
                break;
            case 3: System.out.println("satisfactory");
                break;
            case 4: System.out.println("sufficient");
                break;
            case 5: System.out.println("deficient");
                break;
            case 6: System.out.println("insufficient");
                break;
            default: System.out.println("Not a valid note");
        }
 
    }
}

output

  Please enter a note: 2
  good

on the occasion of the current invasion of Russia in Ukraine

Russian Stop this War
java/control_structures/switch.txt · Last modified: 2024/02/16 01:03 (external edit)

Impressum Datenschutz