Switch Statement | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Switch Statement

Why if I enter in the following code a number less than 0 or greater than 12 it does not display "Out of range"? import java.util.Scanner; public class Program { public static void main(String[] args) { int year; Scanner yearScan = new Scanner(System.in); year = yearScan.nextInt(); if (year >= 1 || year <= 12) { switch (year) { case 1: System.out.println("January"); break; case 2: System.out.println("February"); break; case 3: System.out.println("March"); break; case 4: System.out.println("April"); break; case 5: System.out.println("May"); break; case 6: System.out.println("June"); break; case 7: System.out.println("July"); break; case 8: System.out.println("August"); break; case 9: System.out.println("Septembery"); break; case 10: System.out.println("October"); break; case 11: System.out.println("November"); break; case 12: System.out.println("December"); break; } } else { System.out.println("Out of range"); } } }

26th Dec 2016, 9:36 PM
Amadou Camara
2 Answers
+ 1
Everything is taken by the if statement if (year >= 1 || year <= 12) means ( 0 <=12 ) or (13 >= 1) all are true, it needs only one of the 2 conditions to take it, witch makes it work both ways less than 12 or greater than 1. now there's two options If you want to keep the if statement It's better to use the && condition. Or add a default case in switch for "Out of Range".
26th Dec 2016, 11:55 PM
Marwane Boularab
Marwane Boularab - avatar
0
You don't need to use if condition. import java.util.Scanner; public class Program { public static void main(String[] args) { int year; Scanner yearScan = new Scanner(System.in); year = yearScan.nextInt(); switch (year) { case 1: System.out.println("January"); break; case 2: System.out.println("February"); break; case 3: System.out.println("March"); break; case 4: System.out.println("April"); break; case 5: System.out.println("May"); break; case 6: System.out.println("June"); break; case 7: System.out.println("July"); break; case 8: System.out.println("August"); break; case 9: System.out.println("Septembery"); break; case 10: System.out.println("October"); break; case 11: System.out.println("November"); break; case 12: System.out.println("December"); break; default: System.out.println("Out of range"); } } }
26th Dec 2016, 11:03 PM
Ruslan Yussupov
Ruslan Yussupov - avatar