How to enter Double values in case statement in java [duplicate] - java

This question already has answers here:
switch expression can't be float, double or boolean
(6 answers)
Closed 5 years ago.
I used to check int values in case statements but is there any way check double values too? I can't use If else. This is an assignment. Thank you.

yes, but it won't perform very well. This will work
// don't do this, unless you want readability not performance.
switch(Double.toString(d)) {
case "1.0":
break;
case "Infinity":
break;
}
Instead you should use a series of if/else statements or use a Map<Double, DoubleConsumer> for a long list of doubles.
You can use a NavigableMap for efficient range searches.
NavigableMap<Double, DoubleConsumer> map = new TreeMap<>();
// default value is an assertion error
map.put(Double.NEGATIVE_INFINITY, d -> new AssertionError(d));
double upperBound = 12345;
map.put(upperBound, d -> new AssertionError(d));
// if >= 1.0 then println
map.put(1.0, System.out::println);
public static void select(NavigableMap<Double, DoubleConsumer> map, double d) {
Map.Entry<Double, DoubleConsumer> entry = map.floorEntry(d);
entry.getValue().accept(d);
}

Since double values provide an exact representation only in case when the value can be expressed as a sum of powers of 2 that located "close enough" to each other (within the length of mantissa), and because switch works only with exact matches, you cannot use doubles in a switch in a general case.
The basic reason for it is the same as the need to be careful when using == to compare doubles. The solution is the same as well: you should use a chain of if-then-else statements to find the desired value
if (a <= 0.2) {
...
} else if (a < 0.5) {
...
} else if (a < 0.9) {
...
} else {
...
}
or use a TreeMap<Double,Something> and perform a limit search:
TreeMap<Double,Integer> limits = new TreeMap<Double,Integer>();
limits.put(0.2, 1);
limits.put(0.5, 2);
limits.put(0.9, 3);
...
Map.Entry<Double,Integer> e = limits.ceilingEntry(a);
if (e != null) {
switch(e.getValue()) {
case 1: ... break;
case 2: ... break;
case 3: ... break;
}
}

Switch cases only take byte, short, char, and int. And a few other special cases.
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html

Related

Proper Format for a Switch/Case in a Class

Good Evening,
I created this method for a class. I used a switch/case to execute depending on the value of expression. I included an if-else method for each case. I do get an error on case 1-> switch rules are a preview feature and are disabled by default. I attempted to add a : after case 1 and case 2but my results reached high numbers for the sets. I changed the : to -> and it worked appropriately. Now I am wondering if this was a proper way to set the case statements or should it be written differently.
private void playGame()
{
double winCheck = Math.random();
switch (matchServer) {
case 1 ->{
if (winCheck <= player1WinProb)
player1GamesWon++;
else
player2GamesWon++;
matchServer = 2;
}
case 2 ->{
if (winCheck <= player2WinProb)
player2GamesWon++;
else
player1GamesWon++;
matchServer = 1;
A correct switch statement must use ':'
Also, 'break' is missing. This to avoid executing next cases.
You can add 'default' that means that case 1 and case 2 were not presented.
switch (matchServer) {
case 1:
if (winCheck <= player1WinProb)
player1GamesWon++;
else
player2GamesWon++;
matchServer = 2;
break;
case 2:
if (winCheck <= player2WinProb)
player2GamesWon++;
else
player1GamesWon++;
matchServer = 1;
break;
default:
//If it was not 1 or 2
//Printing the values can help
}

Switch Statement in Java netbeans

I have different fields using the same parameters i.e. same grading scale. I want to use switch statement to return grades for different fields using the same scale. Something like this. I thought that there was something like this: switch (attend, job, initiative) { that would combine the three variables.
int attend = 5;
int job = 5;
int initiative = 5;
switch (attend) {
case 1:
getattendo = 5;
break;
case 2:
getattendo = 4;
break;
case 3:
getattendo = 3;
break;
case 4:
getattendo = 2;
case 5:
getattendo = 1;
break;
default:
getattendo = 0; // null
}
Your help is appreciated.
fmk
Enum works well with switch cases. So, you can define an enum that represents your range of value of it is a finite and reasonable range of values :
public enum OPTIONS {
OPTION1(5, 5, 5),
OPTION2(5, 2, 4),
OPTION3(1, 2, 3),
OPTION4(4, 4, 1);
private final int attend;
private final int jobs;
private final int initiative;
Directive(int attend, int jobs, int initiative) {
this.attend = attend;
this.jobs = jobs;
this.initiative = initiative;
}
// ... optional setters & getters
}
Given your create OPTION Enum, you can use a switch to handle the different cases :
switch (OPTION) {
case OPTION1:
getattendo = 5;
break;
case OPTION2:
getattendo = 4;
break;
case OPTION3:
getattendo = 3;
break;
case OPTION4:
getattendo = 2;
break;
default:
getattendo = 0; // null
break;
}
Note: Your switch is legitimate only if you have a finite number of condition. Otherwise, use a method to calculate your result.
A trick you use utilizes the unary or operation for checking binary digit presence.
This will help get you started on switching according to various conditions.
This is similar to how file permissions work in Linux.
public class ScoreCombinator {
public static final int ATTEND = 1; // binary: 001
public static final int JOB = 2; // binary: 010
public static final int INITIATIVE = 4; // binary: 100
public static void main(String[] args) {
evaluate(ATTEND | INITIATIVE); // Attend and Initiative
evaluate(INITIATIVE | ATTEND | JOB); // Attend, Job, and Initiative
}
private static void evaluate(int value) {
switch (value) {
case ATTEND: {
System.out.println("Attend");
break;
}
case ATTEND | JOB: {
System.out.println("Attend and Job");
break;
}
case ATTEND | JOB | INITIATIVE: {
System.out.println("Attend, Job, and Initiative");
break;
}
case ATTEND | INITIATIVE: {
System.out.println("Attend and Initiative");
break;
}
case JOB: {
System.out.println("Job");
break;
}
case JOB | INITIATIVE: {
System.out.println("Job and Initiative");
break;
}
case INITIATIVE: {
System.out.println("Initiative");
break;
}
}
}
}
Something like switch(a,b,c) is not possible.
If all values are the same, just use one of the valueslandmaybe verify that all values are the same).
However, there are workarounds if you want to switch-case with multiple numbers:
mathematical solution
For example, you could use prime numbers for this. As you only want to switch numbers, this is possible as long as there is a prime number higher than the highest expected value(for attend, prime and job).
Instead of switch(attend, job, initiative), you use switch((attend*prime+job)*prime+initiative) and instead of case (exampleAttend, exampleJob, exampleInitiative):, you use case ((exampleAttend*prime+exampleJob)*prime+exampleInitiative):
Note that prime must be the same in the switch and case statements.
Note that you should test if any of the input numbers is higher than the prime. This would logically lead to the default case but it could lead to collissions.
You may also want to make sure that the prime to the forth power is lower than the max value of the data type or there may be overflows.
On the other side, this method should be more performant than the second.
simple string concadation
Another option is to work with strings. As the string representation of a number is unique (to the number) and it does not contain some characters (like spaces), you can concadate those numbers and use such a character to seperate them.
Instead of switch(attend, job, initiative), you use switch(attend+" "+job+" "+initiative) and instead of case (exampleAttend,exampleJob,exampleInitiative):, you use case (exampleAttend+" "+exampleJob+" "+exampleInitiative):.
This is obviously easier and fail-safer than the first method involving prime numbers but there should be a performance impact as concadating strings is slower than multiplying ints.
Another possibility is to use enums. Look at the other answer by #Hassam Abdelillah
if you want to know how this works. If you like the enum approach, feel free to upvote the other answer.

Most concise way to express this Java conditional without checking a value twice

I have a variable, x.
I want to call a method m() only if x is one of two possible values.
When calling m(), I want to pass an argument to it, whose value depends on the value of x.
Is there a way to do this in Java without checking the value of x more than once, and calling/writing m() in one place only (i.e. not in multiple branches of an if statement)?
One solution I'm entertaining:
switch (x) {
case 1:
y = "foo";
break;
case 2:
y = "bar";
break;
default:
y = null;
break;
}
if (y != null) m(y);
But I can't help but feel this is technically checking x twice, just obscuring this fact by adding a "proxy" for the second check.
(To clarify why the constraints are what they are: when reading code, I have a hard time understanding logic that branches a lot when there is a high degree of duplication between branches - it becomes a game of "spot the difference" rather than simply being able to see what is happening. I prefer to aggressively refactor such duplication away, which is a habit that serves me well in Ruby, JS, and other languages; I'm hoping I can learn to do the same for Java and make code easier for me and others to understand at a glance.)
I'm not sure of what you want to do, but you can maybe use a Map to get the 'y' parameter from 'x'
Map<Integer, String> map = new HashMap<>();
map.put(1, "foo");
map.put(2, "bar");
if (map.containsKey(x)) {
m(map.get(x));
}
Use "goto" or equivalent:
void do_m_if_appropriate() {
// x and y are assumed to be eg. member variables
switch (x) {
case 1:
y = "foo";
break;
case 2:
y = "bar";
break;
default:
return; // this is the "goto equivalent" part
}
m(y);
}
Above is pretty elegant. If necessary, it's also trivial to change it to return true or false depending on if it called m(), or just y or null.
You can also do tricks with loop constructs, though some might say this is abuse of the loop construct, and you should comment it accordingly:
do { // note: not a real loop, used to skip call to m()
switch (x) {
case 1:
y = "foo";
break;
case 2:
y = "bar";
break;
default:
continue; // "goto equivalent" part
}
m(y);
} while(false);
Here's a solution with Optionals (my Java syntax might be slightly incorrect). Note that to you, the code looks like so, but implementation wise, it's similar to the example you posted (i.e. checks whether y is an exceptional value).
switch (x) {
case 1:
y = Optional<String>.of("foo");
break;
case 2:
y = Optional<String>.of("bar");
break;
default:
y = Optional<String>.empty();
break;
}
y.map((m's class)::m);
result = y.orElse( <value result should take if x was invalid> );
Actually it may be better to modify m() to return an Optional and just return empty if y is not valid, but I assume you want to do this check caller-side.
Why not
switch (x) {
case 1:
y = "foo";
m(y);
break;
case 2:
y = "bar";
m(y);
break;
}

Looking for help on creating more efficient way on doing a lot of checks

Note: Not a duplicate of How do I compare strings in java as I am taking about going through some checks to determine if something is inheriting something something else
Is their a better and more efficient way to do this:
As you can see I am inputting 2 strings then checking them of on a list, as if current = three then it returns true for checking for one, two and three
NOTE: these values(one,two,three) are just placeholders for the example in my use their is no relation between them except that they have a different priority.
public boolean checker(String current, String check) {
if (check.equals("one")) {
if (current.equals("one") || current.equals("two")
|| current.equals("three")) {
return true;
}
}
if (check.equals("two")) {
if (current.equals("two") || current.equals("three")) {
return true;
}
}
if (check.equals("three")) {
if (current.equals("three")) {
return true;
}
}
return false;
}
Here are a few pointers
As Frisch mentioned in comments, use .equals rather than == for String comparison.
Use switch/case
switch (check) {
case "one":
if (current.equals("one")) return true;
case "two":
if (current.equals("two")) return true;
case "three":
if (current.equals("three")) return true;
}
Apart from that, there doesn't seem to be much to do.
Two things.
Don't check strings using equality. Use the .equals() method. You can call it off the string literal. So something like this. Calling it off the string literal is safe even with nulls, which is generally a good thing.
if ("one".equals(check))
You can take advantage of Java's short circuit operators && and ||
if ("one".equals(check)) {
if ("one".equals(current) || "two".equals(current) || "three".equals(current)) {
return true;
}
}
Can become
if ("one".equals(check) && ("one".equals(current) || "two".equals(current) || "three".equals(current))) {
return true;
}
Which will be evaluated from left to right. Since the "one".equals(check) is on the far most left, and is &&'ed with the rest of the statement, Java will bail out of the condition checking if "one".equals(check) is not true, and will not evaluate the rest of the statement.
Since you're just returning true or false, you can also take this a step further and reduce all of your if statements into a single one using De Morgan's laws (http://en.wikipedia.org/wiki/De_Morgan's_laws). Generally you state your boolean if statement in the way that is most natural to you, and then you start simplifying it by applying transformations that keep the logical if statement the same.
A good example of this is, stolen from the below link.
In the context of the main method's program body, suppose the following data is defined:
int score, min = 0, max = 20;
boolean bad, good;
Further suppose that a value is assigned to score, perhaps from a keyboard entry, and I would like to test, with a Boolean expression whether the score is a valid number or not. A good score is in the closed range [0 .. 20], which includes 0 and 20.
good = (score >= min && score <= max);
I would like to get the score from the keyboard in a do while loop, so that I can validate the entry. The logic in my control structure is to demand another entry for the score while the entry is bad. I have a definition of a good entry, and I will use definitions of operators and De Morgan's Law to help me write an expression that represents a bad entry.
good = (score >= min && score <= max); // original definition of good from the logic of my task
good = !(score < min) && !(score > max); // by definition, >= means ! < , <= means ! >
good = !(score < min || score > max); // by De Morgan's' Law
bad = !good ; // bad is not good
bad = !!(score < min || score > max); // substituting for good
bad = score < min || score > max; // double negation is dropped
http://fcmail.aisd.net/~JABEL/1DeMorgansLaw.htm
I would like to update you some thing.
1. We can apply switch cases only on primitive data types but not on objects. As string is object we can't use strings in case/switch statement.
I would like to suggest you to enums/maps in this case.
Please find the below sample programm how i implemented using maps.
public static void main(String[] args) {
Map<String,Integer> map = new HashMap<String, Integer>();
map.put("one", 1);
map.put("two", 2);
map.put("three", 3);
String current = "one";
String check = "one";
if(map.get(check)<=map.get(current)){
System.out.println("Our condition is success");
}
}
Instead of multiple comparison this is better.
---Santhosh

How are "ranges" defined in Java?

I have a chunk of code that needs to determine if a given integer is between a set of other integers. I'd also like to have this in a case statement so as to not have a surplus of if..else statements everywhere. Here's a bit of the code:
switch (copies) {
case copies >= 0 && copies <= 99: copyPrice = 0.30; break;
case copies >= 100 && copies <= 499: copyPrice = 0.28; break;
case copies >= 500 && copies <= 749: copyPrice = 0.27; break;
case copies >= 750 && copies <= 1000: copyPrice = 0.26; break;
case copies > 1000: copies = 0.25; break;
}
where copies is an integer and copyPrice is a double. I get several errors saying that it expects to receive a integer but gets a boolean instead. What is the best (or optimal) way of setting this up? Any help is greatly appreciated!
This line (and similar):
case copies >= 0 && copies <= 99:
Returns a compiler error since it gives a boolean but the compiler expects an int since copy is declared as int.
One way to solve this is using an array with the desired ranks, and have a switch statement for the index found:
public double calculateCopyPrice(int copies) {
int[] range = { 99, 499, 749, 1000 };
double copyPrice = 0;
int index = -1;
for (int i = 0; i < range.length; i++) {
if (range[i] >= copies) {
index = i;
break;
}
}
switch (index) {
case 0: copyPrice = 0.30; break;
case 1: copyPrice = 0.28; break;
case 2: copyPrice = 0.27; break;
case 3: copyPrice = 0.26; break;
default: copyPrice = 0.25; break;
}
//probably more logic here...
return copyPrice;
}
After some tests, I've found a more flexible solution using a TreeMap<Integer, Double> which allows you to have a specie of range (what you're looking for) and ease the search by using TreeMap#ceilingEntry:
//TreeMap to store the "ranges"
TreeMap<Integer, Double> theMap = new TreeMap<Integer, Double>();
//add the data
theMap.put(99, 0.3);
theMap.put(499, 0.28);
theMap.put(749, 0.27);
theMap.put(1000, 0.26);
//the "default" value for max entries
theMap.put(Integer.MAX_VALUE, 0.25);
//testing the solution
Double ex1 = theMap.ceilingEntry(50).getValue();
Double ex2 = theMap.ceilingEntry(500).getValue();
Double ex3 = theMap.ceilingEntry(5000).getValue();
Double ex4 = theMap.ceilingEntry(100).getValue();
System.out.println(ex1);
System.out.println(ex2);
System.out.println(ex3);
System.out.println(ex4);
java has no native concept of "ranges", let alone support for them in case statements.
usually, when faced with this kind of logic i personally would do one of 2 things:
just have a chain of if-else statements. doesnt even habe to be a chain:
public static double calculateCopyPrice(int copies) {
if (copies > 1000) return 0.25;
if (copies >= 750) return 0.26;
//etc
}
this code has no "else" branches and is just as much typing as the switch syntax you'd like. possibly even less (i only check a single bound every time)
you could use an enum, say:
public enum Division {UNDER_100, 100_to_500, ... }
and then :
Division division = categorize(copies);
switch (division) {
case UNDER_100:
//etc
}
but this is serious overkill for what youre trying to do. i'd use that if this division is also useful elsewhere in your code.
Switch case function must have an exact number in case. For example:
case 0:
case 1:
You're trying to use case from some value to some value and it's not implemented that way in Java. For your problem, you must use if-else statement since it's impossible to do it with switch case. Hope it helped.
Look the problem is very basic..
In a switch statement it allows only the following datatypes and wrapper classes
Byte,short,char,int,Byte,Short,Character,Integer,enum,String..
If you are passing anything other than that will give you an error.
In your case the condition which you are evaluating will give you result which is a Boolean value.
NavigableMap.seilingEntry() may be a good solution in many cases,
but in other cases the following may be clearer:
double getPrice(int copies){
return copies>1000 ? 0.25
: copies>750 ? 0.26
: copies>500 ? 0.27
: copies>100 ? 0.28
: copies>0 ? 0.30
: 0; // or check this condition first, throwing an exception
}

Categories