Options

Java Switch statement

Haruna Umar AdogaHaruna Umar Adoga Member Posts: 24 ■□□□□□□□□□
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"); }}}

Comments

  • Options
    NotHackingYouNotHackingYou Member Posts: 1,460 ■■■■■■■■□□
    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.
    When you go the extra mile, there's no traffic.
  • Options
    NotHackingYouNotHackingYou Member Posts: 1,460 ■■■■■■■■□□
    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.
  • Options
    Haruna Umar AdogaHaruna Umar Adoga Member Posts: 24 ■□□□□□□□□□
    Thanks for your help, I have figured it out
  • Options
    NotHackingYouNotHackingYou Member Posts: 1,460 ■■■■■■■■□□
    Can you post your result?
    When you go the extra mile, there's no traffic.
Sign In or Register to comment.