Reputation:
can't seem to find the syntax mistake in this switch statement. Any help is much appreciated.
Source code:
import java.util.Scanner;
public class SwitchCasing {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
try {
int number = Integer.parseInt(input);
switch(number) {
case 1:
if(number < 0) {
System.out.println("Number is smaller than 0.");
break;
}
case 2:
if(number > 0){
System.out.println("Number is greater than 0.");
break;
}
default:
System.out.println("Number is 0.");
}
} catch(IllegalArgumentException e) {
System.out.println("Please insert a valid number.");
}
sc.close();
}
}
The output is always "Number is 0", no matter what value is entered. Thanks!
Upvotes: 0
Views: 690
Reputation: 4945
case 1:
means that number equals 1. But since 1 is not less than 0 you'll never see "Number is smaller than 0.", and you won't break. (The break
is inside the if (number < 0)
part).
case 2:
means that number equals 2. You'll enter this case if you enter a 2.
That leaves default
for all other values you might enter, which I'm guessing are most of them.
You really don't want a switch
in this situation. You should be using an if-else
construct, like this:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
try{
int number = Integer.parseInt(input);
if(number < 0) {
System.out.println("Number is smaller than 0.");
} else if(number > 0) {
System.out.println("Number is greater than 0.");
} else {
System.out.println("Number is 0.");
}
} catch(IllegalArgumentException e) {
System.out.println("Please insert a valid number.");
} finally {
sc.close();
}
}
Upvotes: 0
Reputation: 72
As first, do you know you can do int number = sc.nextInt();
you do not need to parse the input and it assures that the user gives you a int.
As for your switch case your break; are inside if statements so when the code reads break it breaks our of the loop containing it. In your case it breaks out of the if/else statement not the switch case.
Hope I could help!
Upvotes: 0
Reputation: 178333
Those case labels aren't for you labeling purposes; they are for Java to compare number
so it can execute the case.
It will start execution at the block for case 1:
if number
is 1
. Because 1
isn't less than 0
, that block won't produce any output.
It will start execution at the block for case 2:
if number
is 2
. Because 1
isn't less than 0
, that block will produce the output "Number is greater than 0.".
Any other number will go to the default case and produce the output "Number is 0.", even though your output is incorrect.
You can't test cases that way with a switch statement. Change it to the equivalent if/else construct.
if(number < 0){
System.out.println("Number is smaller than 0.");
}
else if(number > 0){
System.out.println("Number is greater than 0.");
}
else {
System.out.println("Number is 0.");
}
Upvotes: 6