Home
Certification Preparation
Other Certifications
Sun Microsystems Java Certification
Java Switch statement
Haruna Umar Adoga
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"); }}}
Find more posts tagged with
Comments
NotHackingYou
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.
NotHackingYou
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.
Haruna Umar Adoga
Thanks for your help, I have figured it out
NotHackingYou
Can you post your result?
Quick Links
All Categories
Recent Posts
Activity
Unanswered
Groups
Best Of