+ 2
I need a program to find out the signe of a number (equal =0,>or <0) using switche statements
If number >0 show positif If number <0 show negative else zero( using switch statement )
11 Answers
+ 1
Or I have an idea:
int num /= Math.abs(num);
switch(num){
case 1:
...Positive
Break;
case -1:
....Negative
Break;
Default:
Null
}
0
So you need to find wich number is negative, or positive, then you want to calculate the signe of the current number?
0
The switch is not good in this case, but if you want with switch...(in java):
int num = 1;
switch(num<0){
case true:
System.out.println("It is negative");
break;
case false:
switch(num==0){
case true:
System.out.println("the number is 0");
break;
case false:
System.out.println("the number is positive");
break;
}
break;
}
0
With tarnary operator is much easier:
int num = 1;
System.out.println("The number is "+num<0?"negative":num==0?"0":"positvie);
0
import java.util.Scanner;
public class EXO5METHODE2 {
public static void main(String[] args) {
double nbr;
Scanner entree = new Scanner(System.in);
System.out.println("Entrez un nombre entier relatif : ");
nbr=entree.nextDouble();
switch (nbr<0) {
case true:
System.out.println("le nombre que vous avez entré est negative !");
break;
case false:
switch(nbr==0) {
case false:
System.out.println("le nombre que vous avez entré est nul !");
break;
default:
System.out.println("le nombre que vous avez entré est positif !");
clavier.close();
} }}}
0
I try but the program doesn't work !
0
What is the output? Or what is the error message?
0
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Cannot switch on a value of type boolean. Only convertible int values, strings or enum variables are permitted
Cannot switch on a value of type boolean. Only convertible int values, strings or enum variables are permitted
clavier cannot be resolved
at EXO5METHODE2.main(EXO5METHODE2.java:8)
0
Because in switch method cannot add boolean as parameter, so you cant solve this with switch, because the boolean has only 2 value, true and false
0
Try solve with tarnary operator, or with a simple if method, anyway nobody prefered switch method, because switch has jumping instuction, and the jumping instruction is not the safest thing
0
I use your idea (nbr/math.abs(nbr)) for switch method and thanks for helping