+ Reply to Thread
Results 1 to 5 of 5
  1. Junior Member Haruna Umar Adoga's Avatar
    Join Date
    Jul 2009
    Location
    Hatfield, United Kingdom
    Posts
    22

    Certifications
    ITILv3, CCNA, CCNP, Beng Elect Elect Engineering
    #1

    Default Java Switch statement

    I need help with how to replace the if else statements in this program with a switch statement. Positive response will be appreciated

    import java.util.Scanner;
    public class Switch {
    public static void main(String [] args){

    // create new Scanner
    Scanner input = new Scanner(System.in);
    System.out.println("Enter an integer: ");
    int value = input.nextInt();
    //executute the if else statements for desired output

    if (value % 5 == 0) {
    System.out.println("HI FIVE");
    }
    else if (value % 2 == 0) {
    System.out.println("HI EVEN"); }
    else { System.out.println("The ineger value you entered is neither even nor odd"); }}}
    Last edited by Haruna Umar Adoga; 01-29-2013 at 10:18 PM.
    Reply With Quote Quote  

  2. SS -->
  3. Achieve excellence daily
    Join Date
    May 2012
    Location
    Washington State
    Posts
    1,363

    Certifications
    CISSP
    #2
    Here's a basic case statment in Java:

    int intMonth = 1;

    String strMonthName;

    switch (intMonth) {

    case 1: strMonthName = "Jan";
    break;

    case 2: strMonthName = "Feb";
    break;
    (continue all valid cases)

    default: strMonthName = "This is not a valid month"; //if it doesn't match any of the above, it will use this
    break;

    }

    I didn't look through the code you posted because it was all slammed together.
    Last edited by NotHackingYou; 01-29-2013 at 10:26 PM.
    When you go the extra mile, there's no traffic.
    Reply With Quote Quote  

  4. Achieve excellence daily
    Join Date
    May 2012
    Location
    Washington State
    Posts
    1,363

    Certifications
    CISSP
    #3
    My understanding of switch is that it is used to evaluate one expression for seperate conditions. You are using two seperate expressions. Switch is used for cases like String strAnimal = "goat". Is the animal a goat? A chicken? A dog? So in my understanding a switch is not the appropriate statement for what you are tying to do.
    When you go the extra mile, there's no traffic.
    Reply With Quote Quote  

  5. Junior Member Haruna Umar Adoga's Avatar
    Join Date
    Jul 2009
    Location
    Hatfield, United Kingdom
    Posts
    22

    Certifications
    ITILv3, CCNA, CCNP, Beng Elect Elect Engineering
    #4
    Thanks for your help, I have figured it out
    Reply With Quote Quote  

  6. Achieve excellence daily
    Join Date
    May 2012
    Location
    Washington State
    Posts
    1,363

    Certifications
    CISSP
    #5
    Can you post your result?
    When you go the extra mile, there's no traffic.
    Reply With Quote Quote  

+ Reply to Thread

Social Networking & Bookmarks