Elegant way to code if (10 < x < 20) - java

Is there an elegant way in Java to code:
if (10 < x < 20) {
...
}
i.e. "if x is between 10 and 20"
rather than having to write
if ((x > 10) && (x < 20)) {
...
}
Thanks!

No. The < operator always compares two items and results in a boolean value, so you cannot chain them "elegantly". You could do this though:
if (10 < x && x < 20)
{
...
}

Kenny nailed it in the comments.
if (10 < x && x < 20)
You want to keep them either both less-than or both greater-than; reversing the direction of the comparison makes for a confusing bit of logic when you're trying to read quickly.

No but you can re-arrange it to make it better, or write a wrapper if it irks you:
if (InRange(x, 10, 20)) { ... }
Or, as Carl says:
if (new Range(10, 20).contains(x)) { ... }
Though personally, I don't see the point. It's a useless abstraction. The bare boolean statement is perfectly obvious.
Though, now that I think about it, and in light of Carl's comment below, there are times when a Range is a perfectly valid and useful abstraction (e.g. when dealing with Feeds). So, depending on the semantics of x, maybe you do want an abstraction.

if(x < 20)
{
if(x > 10)
{
//...
}
}
OR
if(x > 10)
{
if(x < 20)
{
//...
}
}

The only thing you can do is loose the extra parenthesis since the && has a lower precedence than > and <:
if (x > 10 && x < 20) {
...
}
Other than that: there's no shorter way.

The FASTEST way is a switch.
EDIT:
switch(x) {
case 10:
case 11:
case 12:
case 13:
...
case 19: System.out.println("yes");
}
is compiled into a jump table, not a long series of ifs.

Related

How to convert if-statements to switch statements

My code is supposed to convert scores to letter grades, so I used if statements. Just wondering if there's a way to use a switch statement instead of if-statements. I have no idea how to convert it. Also, is one better than the other?
public static void determineGrade(int numArray[], char letterArray[]) {
int scoreCount = numArray.length;
for (int i=0; i < scoreCount; i++) {
if (numArray[i] >= 90 && numArray[i] <=100) {
letterArray[i] = 'A';
}
if (numArray[i] >= 80 && numArray[i] < 90) {
letterArray[i] = 'B';
}
if (numArray[i] >= 70 && numArray[i] < 80) {
letterArray[i] = 'C';
}
if (numArray[i] >= 60 && numArray[i] < 70) {
letterArray[i] = 'D';
}
if (numArray[i] >= 0 && numArray[i] < 60) {
letterArray[i] = 'F';
}
}
displayTestScores(numArray, letterArray);
public char getGrade(int input){
switch(input/10)
{
case 9: return 'A';
case 8: return 'B';
case 7: return 'C';
case 6: return 'D';
default: return 'F';
}
}
Then
for (int i=0; i < scoreCount; i++) {
letterArray[i] = getGrade(numArray[i]);
}
You can switch statement in this case but I wouldn't recommend due to the fact you will have way too many cases. You will use at least 100 cases to input because of your if statement conditions.
case 100 ://code
break;
case 50 ://skip a bit
case 0 :
There is way too many cases and a waste of time and lines.
Your conditions are ranges. Java switch statements have cases for values, not ranges.
Since you have a limited number of cases, you could list each one of them independently. However, this would make your code much longer, with 100 cases.
And there's also some math trickery you could do to find the lower number divisible by 10, and switch on that. But the if statement is simpler to implement and read.
All that said, your second expression in the if statements is unnecessary, if you use an else statement, not an independent if. And you want to use an else, because it would be silly to continue checking all the remaining cases after the first one whose condition is met.
if (numArray[i] >= 90 ) { // Can you have values > 100?
letterArray[i] = 'A';
}
else if (numArray[i] >= 80 ) { // If we're checking this, we know numArray[i] < 90
letterArray[i] = 'B';
}
else if ...
You're looking to produce a switch statement that has cases based on ranges. It's not really what switch statements are meant for. the if route is more elegant/a better solution for your case imo.
In Java,Using switch statement with a range of value in each case?

Calculating how far a robot will move in Java

I'm working on a project for school that requires me to move a robot. How far the robot will move each second (variable t) is calculated by the function below.
The first function is easy. The 2nd and 3rd on the other are where I'm stuck. How would I write F(t-1)? Below is what I have so far.
if (t == 0) {
distance = 2;
} else if (t > 0 && <=6 || t > 12) {
// No clue on how to write the 2nd distance equation.
} else if (t >= 7 && <=12) {
// No clue on how to write the 3rd distance equation.
}
Recursion really isn't necessary to solve this.
Note that in each of the non-zero time cases, F(t) = F(t-1) + something.
So you can simply do:
double f = 2; /* Initial value at t=0 */
for (int t = 1; t <= maxT; ++t) { // maxT is the maximum value of t.
if (t <= 6 || t > 12) {
f += /* something for case 2 */;
} else {
f += /* something for case 3 */;
}
}
System.out.println(f);
You can do this with recursion, but you will get a StackOverflowError if maxT becomes modestly large; by contrast, using a loop will work for arbitrarily large maxT (modulo floating point errors).
As pointed out by #Andreas, you can do this without looping over all values of t:
double f = 2 * (maxT + 1);
for (int t = 7; t <= maxT && t <= 12; ++t) {
f += log(t) - 2;
}
and you can eliminate that loop too by precomputing the values.
This is a problem which involves the use of recursion. By and large, pay close attention to the notation Ft-1, since that refers to an evaluation of the specific function at t-1.
I won't write out all of the code, but I'll give you some of the basics:
When t = 0, return 2. This is your base case.
When t is between 0 and 6 inclusive or greater than 12, return an evaluation of the function at t-1 and add 2.
When t is between 7 and 12 both inclusive, return an evaluation of the function at t-1 and add log2(t).
Here's something to get you at least started in the right direction.
public double evaluateDistance(int t) {
if(t == 0) {
return 2;
} else if(t > 0 && t <= 6) || (t > 12) {
// Think about this - it would involve another call to evaluateDistance, but what is t again?
} else if(t >= 7 && t <= 12) {
// Another evaluation involving the function.
// For free, the change of base operation you'll need to get base-2 evaluation for the log:
return ??? + Math.log(t)/Math.log(2);
}
}
Think I figured it out. Sorry if I wasn't clear on what I needed, just needed to figure out how to write the equations in the function. Think I figured it out though.
public double move()
{
int t = 0;
if(t == 0) // After the first second, robot moves 2
{
distance = 2;
}
else if(t > 0 && t <= 6 || t > 12) // From seconds 0 to 6 and after 12, robot moves distance equation
{
distance = (2*t)+2;
}
else if(t >= 7 && t <= 12) // From seconds 7 to 12, robot moves distances equation
{
distance = (2*t)+(Math.log(t)/Math.log(2));
}
position = position + distance;
return position;
}
}

Ternary Operators(Java)

I was recently introduced to ternary operators. I managed to make it through a year and a half of CS school without a professor ever mentioning ternary operators. This is my first quarter where my professor is using them regularly. They seem great for shortening code. So, this is a question that will help me understand the bounds of ternary operators and when/how they can be used. Is there a way to shorten the following code block using one long statements using a ternary operator?
if(age < 18){
minors+=1;
} else if(age < 65){
adults+=1;
}else{
seniors+=1;
}
You are updating three unique variables, one way to use ternaries here is something like
minors += (age < 18) ? 1 : 0;
adults += (age >= 18 && age < 65) ? 1 : 0;
seniors += (age >= 65) ? 1 : 0;
You can write it as a single statement:
int dummy = (age < 18) ? (minors += 1)
: (age < 65) ? (adults += 1)
: (seniors += 1);
The value of dummy is unused here. It's just a way to turn the expression into a statement.
Note that I wouldn't consider writing the logic like this in practice. There are multiple side-effects in the code, and that makes it hard to understand.
I think the intent of your current code is very clear as written. Ternary expressions have a tendency to make the code harder to read, in my experience.
The ternary operator is not a good fit for your code because you are changing 3 different variables. I would leave your code as it is.
Suppose, on the other hand, that you had this
if (age < 18) {
number += 1;
} else if (age < 65) {
number = 8;
} else if (age < 90) {
number += 2;
} else {
number = 13;
}
This could be rewritten to look like a kind of switch:
number = age < 18 ? number + 1 :
age < 65 ? 8 :
age < 90 ? number + 2 :
13;
I think this is an improvement on the if version. However, it is not common to nest ternary operators in this way, so you may confuse people looking at your code if you used this version.

Convert Integer to int in Java

I find a very weird situation when writing Java code:
Integer x = myit.next();
if ((int)x % 2 == 0) {
In which myit is an Iterator and x is an Integer.
I just want to test whether x is an even number or not. But x % 2 == 0 does not work since eclipse says % not defined on Integer. Then I try to convert x to int by explicitly converting. Again, it warns me that not able to convert in this way.
Any reason why it happened and what is the right way to test if x is even ?
UPDATE:
ANYWAY,I test it that the following code works, which means all of you guys are right.
Integer x = 12;
boolean y = ( (x % 2) == 0 );
boolean z = ( (x.intValue() % 2) == 0 );
I think the problem I have before may be the context of the code. It is late night, I would update later if I find why would that thing happen.
Use :
if (x.intValue() % 2 == 0)
PS : if(x % 2==0) should also work because integer.intValue() should be called internally.
Byte code for :if(x % 2==0)
11: invokevirtual #23; //Method java/lang/Integer.intValue:()I --> line of interest
14: iconst_2
15: irem
x % 2 == 0 does not work since eclipse says % not defined on Integer
This is not true. You can use % with Integer
take a look at this
Integer x = new Integer("6");
if (x % 2 == 0) {
System.out.println(x);
}
Out put:
6
You should read about Integer in Java
public static void main(String[] args) {
List<Integer> myList = new ArrayList<Integer>();
myList.add(21);
myList.add(22);
myList.add(41);
myList.add(2);
Iterator<Integer> itr = myList.iterator();
while (itr.hasNext()) {
Integer x = itr.next();
if (x % 2 == 0) {
System.out.println("even");
} else {
System.out.println("odd");
}
}
}
Output
odd
even
odd
even
Use this:
if(((int)x)%2==0){
Note: one more (

is it possible to use this switch statement in Java

C++ has a very handy switch statement, but I don't know if this is possible is java
switch(num)
{
case 1 ... 9:
do something
break
case 10 ... 19:
do something
break
default: something
}
is this possible in java, I've tried, but it doesn't work, at least not like c++, is there an equivalent for this?
thanks
Java's switch statement requires you to explicitly list all values that you match (except for the default: clause, of course). If you're doing substantial ranges, it is probably better to use a chain of ifs:
if (num >= 1 && num <= 9) {
do_something_A
} else if (num >= 10 && num <= 19) {
do_something_B
} else {
do_something_C
}
If your real num has side effects (or is plain expensive to compute), evaluate it once and save it to a local variable, then use that local in the chain of tests.
No, it's not possible. Probably the most straightforward equivalent is:
if (num >= 1 && num <= 9)
doSomething();
else if (num >= 10 && num <= 19)
doSomethingElse();
else
doDefault();
Marginal cleanup could be defining an inRange utility function and using it inside the if statements:
boolean inRange(int num, int min, int max) {
return num >= min && num <= max;
}
...
if (inRange(num, 1, 9))
doSomething();
else if (inRange(num, 10, 19))
doSomethingElse();
else
doDefault();
Java have switch statement, but you have to use it in this way :
switch(num)
{
case 1:
case 2:
case 3:
case 4:
//And so far with cases
//do something
break
case 10:
case 11:
case 12:
//And so far ...
//do something
break
default: something
}
Yes, there is a switch statement in Java. It is in fact quite similar to switch in C++.
However, neither C++ nor Java support ranges in case labels.
For the specific example that you present I would use a series of if statements:
if (num >= 1 && num <= 9) {
...
} else if (num >= 10 && num <= 19) {
...
} else {
...
}
No Java does not, in a situation like this it would be much more practical to use a series of if-else statements. :)
if(num >= 1 && num < 10) {
//do something
} else if(num >= 10 && num < 20) {
//do something
} else {
//do something
}
The feature you are talking about doesn't really belong to C++, it is a language extension which is present, for example, in GCC. But normally in C++ ranges are checked using if...else, and the same technique should be used in Java:
if (num >= 1 && num <= 9) {
//Do something
} else if (num >= 10 && num <= 19) {
//Do something else
} else {
//Do something by default
}
No, ranges are not allowed you would need to use an if else structure.

Categories

Resources