0

Here is my if-else statement:

public static void main(String[] args) { Scanner input = new Scanner (System.in); int number; System.out.println("Enter Integer: "); number = input.nextInt(); if (number % 7 == 0) { System.out.println(number + " is divisible by 7"); } else { System.out.println(number + " isn't divisible by 7"); } } 
3
  • 5
    The switch Statement. Commented Feb 5, 2014 at 7:37
  • 1
    What do you need switch for? you either have divisioble or not Commented Feb 5, 2014 at 7:39
  • 2
    Smells like a homework assignment. Why else would someone write code like this and then want to turn it into a switch statement. Commented Feb 5, 2014 at 7:43

5 Answers 5

6

Never mind the switch - you don't need either.
You can make it into one statement:

System.out.println(number + " is" + (number % 7 == 0 ? "" : "n't") + " divisible by 7"); 
Sign up to request clarification or add additional context in comments.

Comments

3
number = input.nextInt(); switch(number % 7) { case 0: System.out.println(number + " is divisible by 7"); break; default: System.out.println(number + " isn't divisible by 7"); } 

Comments

0
 number = input.nextInt(); a = number % 7 switch (a) { case 0: System.out.println(number + " is divisible by 7"); break; default: System.out.println(number + " isn't divisible by 7"); break; } 

Comments

0

Check this out:

 switch (number % 7) { case 0: System.out.println(number + " is divisible by 7"); break; default: System.out.println(number + " isn't divisible by 7"); } 

OR

switch (number % 7) { case 0: System.out.println(number + " is divisible by 7"); break; case 1: // Fall through case 2: case 3: case 4: case 5: case 6: System.out.println(number + " isn't divisible by 7"); } 

Comments

0

Try like this;

Scanner input = new Scanner (System.in); int number; System.out.println("Enter Integer: "); number = input.nextInt(); int tempNumber = number % 7; switch(tempNumber) { case 0: System.out.println(number + " is divisible by 7"); break; default : System.out.println(number + " isn't divisible by 7"); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.