Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 7 of 7

Thread: How to Use the Java switch statement

  1. #1
    mmm.. coffee JavaPF's Avatar
    Join Date
    May 2008
    Location
    United Kingdom
    Posts
    3,336
    My Mood
    Mellow
    Thanks
    258
    Thanked 294 Times in 227 Posts
    Blog Entries
    4

    Post How to Use the Java switch statement

    This example shows you how to use the Java switch statement.

    Unlike if-then and if-then-else, the switch statement allows for any number of possible execution paths. A switch works with the byte, short, char, and int primitive data types.

    public class SwitchCase {
     
        /**
         * JavaProgrammingForums.com
         * Spread the word ;)
         */
     
        public static void main(String[] args) {
     
            int day = 5;
     
            switch (day) {
                case 1:  System.out.println("Monday"); break;
                case 2:  System.out.println("Tuesday"); break;
                case 3:  System.out.println("Wednesday"); break;
                case 4:  System.out.println("Thursday"); break;
                case 5:  System.out.println("Friday"); break;
                case 6:  System.out.println("Saturday"); break;
                case 7:  System.out.println("Sunday"); break;
                default: System.out.println("Invalid Day.");break;
            }
        }
    }
    Example output:

    Friday
    Please use [highlight=Java] code [/highlight] tags when posting your code.
    Forum Tip: Add to peoples reputation by clicking the button on their useful posts.


  2. #2
    Super Moderator Json's Avatar
    Join Date
    Jul 2009
    Location
    Warrington, United Kingdom
    Posts
    1,274
    My Mood
    Happy
    Thanks
    70
    Thanked 156 Times in 152 Posts

    Default Re: How to Use the Java switch statement

    Other than primitives you can also switch on enums

    public class SwitchCase {
     
        /**
         * JavaProgrammingForums.com
         * Spread the word ;)
         */
     
        public enum Day {
            MONDAY,
            TUESDAY,
            WEDNESDAY,
            THURSDAY,
            FRIDAY,
            SATURDAY,
            SUNDAY,
        }
     
        public static void main(String[] args) {
            final Day day = Day.values()[new Random().nextInt(Day.values().length)];
     
            switch (day) {
                case MONDAY: {
                    System.out.println("Its Monday");
                    break;
                }
                case TUESDAY: {
                    System.out.println("Its Tuesday");
                    break;
                }
                case WEDNESDAY: {
                    System.out.println("Its Wednesday");
                    break;
                }
                case THURSDAY: {
                    System.out.println("Its Thursday");
                    break;
                }
                case FRIDAY: {
                    System.out.println("Its Friday");
                    break;
                }
                case SATURDAY: {
                    System.out.println("Its Saturday");
                    break;
                }
                case SUNDAY: {
                    System.out.println("Its Sunday");
                    break;
                }
                default: {
                    System.out.println("what day is it?");
                    break;
                }
            }
        }
    }


    Example output:
    Its Monday
    Its Saturday
    // Json

  3. The Following User Says Thank You to Json For This Useful Post:

    Fendaril (August 30th, 2009)

  4. #3
    Java kindergarten chronoz13's Avatar
    Join Date
    Mar 2009
    Location
    Philippines
    Posts
    659
    Thanks
    177
    Thanked 30 Times in 28 Posts

    Default Re: How to Use the Java switch statement

    i just want to add a liitle bit with switch in enum types,, i added some code on how to input a String value and switch it as an enum type using .valueOf() method

    import java.util.*;
     
    /**
     *
     * @author  algorithm by JSon
     * @author  coded by chronoz13
     */
     
    public class SwitchEnumType {
     
         private static Scanner sc = new Scanner(System.in);
     
         private static enum Days {SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY}
     
         public static void main(String[] args) {
     
             String keyIn;
     
             System.out.println("Enter the day: ");
             keyIn = sc.next();
     
             Days days = Days.valueOf(keyIn);
     
             switch(days) {
     
                 case SUNDAY:
     
                     System.out.println("Today is Sunday");
                     break;
     
                 case MONDAY:
     
                     System.out.println("Today is Saturday");
                     break;
     
                 case TUESDAY:
     
                     System.out.println("Today is Tuesday");
                     break;
     
                 case WEDNESDAY:
     
                     System.out.println("Today is Wednesday");
                     break;
     
                 case THURSDAY:
     
                     System.out.println("Today is Thursday");
                     break;
     
                 case FRIDAY:
     
                     System.out.println("Today is Friday");
                     break;
     
                 case SATURDAY:
     
                     System.out.println("Today is Saturday");
                     break;
     
                  default:
     
                      System.out.println("Say What? Make Your Own Calendar!");
                      break;
             }
         }
    }

    NOTE: make sure that the case of the string that will be input is exactly the same as the enum type.
    Last edited by chronoz13; October 9th, 2009 at 10:48 AM.

  5. #4
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: How to Use the Java switch statement

    Please note that there is one problem with your code:

    You forgot to implement the valueOf function inside the enum

  6. #5
    Super Moderator Json's Avatar
    Join Date
    Jul 2009
    Location
    Warrington, United Kingdom
    Posts
    1,274
    My Mood
    Happy
    Thanks
    70
    Thanked 156 Times in 152 Posts

    Default Re: How to Use the Java switch statement

    The valueOf method is an inherited method for enums and will work without an override.

    // Json

  7. #6
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: How to Use the Java switch statement

    I did not know that.

  8. #7
    Junior Member
    Join Date
    Apr 2013
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Talking Re: How to Use the Java switch statement

    Try The Code Below And I have added toUpperCase so that it can read from user either lowercase and uppercase,
    But i can't insert it inside the case monday and i have replace it with int num, so may i know what are the solutions ?
    Please comment about my code cause i'm just a beginner in Java

    import java.util.Scanner;
     
    public class application {
     
    	private static Scanner myMachine;
    	private static Scanner myMachine2;
     
    	public static void main(String[] args) {
     
    		myMachine = new Scanner(System.in);
    		myMachine2 = new Scanner(System.in);
     
    		System.out.println("Please Enter The Weekday Of Today: ");
    		String command = myMachine.nextLine();
    		command = command.toUpperCase();			
     
               switch (command){
     
    		case "MONDAY":
    			System.out.println("Monday is a Working Days !\n");
    			System.out.println("Are You Feeling Tired Today ?\n");
    			System.out.println("Answer 1 = Yes\n" + "Answer 2 = No");
    			int num = myMachine2.nextInt();
    			if (num == 1){
    				System.out.println("Ohh So Pity !");
    			}
    			else
    			{
    				System.out.println("So WORK MORE HARDER !!!!!!!!!!!!");
    			}
    			break;			
     
    		case "TUESDAY":
    			System.out.println("OMG TUESDAY ARE HORRIBLE!");
    			break;
    		case "WEDNESDAY":
    			System.out.println("HAHA Its Nice Weekdays For You.");
    			break;
    		case "THURSDAY":
    			System.out.println("Ohh Today's Are Weekday !");
    			break;
    		case "FRIDAY":
    			System.out.println("Beware Of Black Friday !");
    			break;
    		case "SATURDAY":
    			System.out.println("Lets Go For Fun Today !");
    			break;
    		case "SUNDAY":
    			System.out.println("Its A Rest Day");
    			break;
    		default:
    			System.out.println("You Have Enter unrecognized command !");
     
    		}
     
    	}	
    }

Similar Threads

  1. If statement
    By Dave in forum Loops & Control Statements
    Replies: 2
    Last Post: August 27th, 2009, 10:11 AM
  2. Error of "Class has no return statement"
    By mdstrauss in forum What's Wrong With My Code?
    Replies: 7
    Last Post: August 2nd, 2009, 12:00 PM
  3. [SOLVED] Switch statement question
    By shikh_albelad in forum Loops & Control Statements
    Replies: 5
    Last Post: May 31st, 2009, 05:13 AM

Tags for this Thread