Does a simpler representation of this if condition exist? - java

I used the below conditional statement to ensure that the city name given is of valid length. Length of city should be greater than or equal to 3 and less than or equal to 20.
if(city.length()<3 || city.length()>20) return false;
else return true;
I am told that this conditional statement can be further simplified. Is that right? Then what is the simplified code?

return !(city.length() < 3 || city.length() > 20)
or
return city.length() >= 3 && city.length() <= 20

I simplified your code from IntelliJ IDEA IDE.
Actually it itself suggested to simplify when I used your code there. I recommend you to try IntelliJ IDEA.
return city.length() >= 3 && city.length() <= 20;
If you are already using the IDE, just move the cursor to the code with warning and press ALT+Enter and simplify it.

If city.length() is cheap, then write
return city.length() >= 3 && city.length() <= 20
else you ought to pre-compute city.length() to avoid the potential for two evaluations:
const auto&& /*assuming C++, for Java, you need to use the specific type*/ l = city.length();
return l >= 3 && l <= 20;

Related

I am writing a java program that uses one loop to process the integers from 300 down to 200

Here are my instructions:
Write a program that uses one loop to process the integers from 300 down to 200, inclusive. The program should detect multiples of 11 or 13, but not both. The multiples should be printed left-aligned in columns 8 characters wide, 5 multiples per line. When all multiples have been displayed, the program should display the number of multiples found and their sum.
int sum = 300;
while (sum >= 200 && sum <= 300 ) {
sum = sum - 1;
System.out.println( sum % 11 == 0 || sum % 13 == 0 );
}
As you may know, I am getting true and false responses rather than the numbers. I am very much stuck and would like any help or advice I can get! Thank you.
The problem is that the == operator is an equality operator that returns a condition (either true or false). That's why you're printing true and false. If you want to print the actual multiples, first check if they are either a multiple of 11 or a multiple of 13 (but not both), and then print the number, sum.
int sum = 300;
while (sum >= 200 && sum <= 300 ) {
if((sum % 11 == 0) != (sum % 13 == 0)) { //checks if sum is a multiple of 11 or 13 but not both
System.out.println(sum);
}
sum = sum - 1;
}
What (sum % 11 == 0) != (sum % 13 == 0) means is that if sum is a multiple of both 11 and 13, then the expression will equate to false because the results of (sum % 11 == 0) and (sum % 13 == 0) are both true. Similar reasoning will let you see that if sum is only a multiple of one of 11 or 13, then the expression will result in true since one side of the expression will result in true while the other side will result in false.
Since this looks like homework, I don't want to just give the answer away, but I'd like to help, so I'll give you a couple of hints:
1) "if" statements are where you'd want to use comparisons to decide what to do, e.g.
if (blah == more_blah)
2) Since your numbers are all guaranteed to be 3 characters, there is a simple and easy way to get the exact spacing of 8 characters per column. (Hint: print() and println() are both things)
3) Since you want multiple columns, you might want some way to check how many columns you have already and then decide whether you want println or print. (bonus hint: using System.out.println("") could make your code simpler.)

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.

Java difference between || and && in this example

I am making a counter between number ranges and not sure the correct way to do this. I have always used the || operator but reading some examples, I feel I should be using the && command. Here is my example problem...
if(value >= 1 || value <=10){
count1++;
}
else if(value >= 11 || value <= 20){
count2++;
// AND SO ON........
Or should I be using the && operator like
if(value >= 1 && value <= 10){
count1++;
}
else if value >= 11 && value <= 20){
count2++;
}
|| means "or".
&& means "and".
value >= 1 || value <= 10 makes no sense because it's always true. All numbers are 1 or more, or 10 or less. Some numbers are both, but that doesn't matter.
value >= 1 && value <= 10 makes far more sense. There's a limited range of numbers ([1..10]) for which both the first condition and the second condition are true.
|| is the or operator, so the condition value >= 1 || value <=10 is true for all values if you think about it. So, unless you want your counts to be meaningless, use && which is the and operator.

Supposed variable cannot be resolved as variable?

I'm doing a basic Java tutorial and below is the question.
Write a method that prints the numbers from 1 to 100. But for multiples of three print ÒFizzÓ instead of the number,and for the multiples of five print ÒBuzzÓ. For numbers which are multiples of both three and five print ÒFizzBuzzÓ."
My code is below
public static void fizzBuzz(){
for(int i = 0; i < 101; i= i +1 )
System.out.println(i);
if (i%3 == 0){
System.out.println("ÒFizzÓ");
}else if (i % 5 == 0){
System.out.println("ÒBuzzÓ");
}else if (i % 15 == 0){
System.out.println("ÒFizzBuzzÓ");
}
}
Eclipse tells me that "i" cannot be resolved as a variable. This is confusing to me as I thought I already defined "i" as an integer in my for loop? Thanks for taking the time to solve this newbie question :)
Add braces or your loop body ends after the first statement. Also, for your approach you need to test 15 first because it's a multiple of 3 and 5
for(int i = 0; i < 101; i++) { // <-- i++ is short for i = i + 1
System.out.println(i);
if (i % 15 == 0) {
System.out.println("ÒFizzBuzzÓ");
} else if (i % 5 == 0) {
System.out.println("ÒBuzzÓ");
} else if (i % 3 == 0) {
System.out.println("ÒFizzÓ");
}
}
I know a funny story about Apple who lost a few million dollars because a developer updated a code with an if block but... the if statement had only one instruction and no curly brackets and he did not see it. Thus, the code he was willing to add when the condition was met were actually ALWAYS executed.
In your case, you won't lose money but you surely did the same mistake :
for(int i = 0; i < 101; i= i +1 ) {
System.out.println(i);
if (i % 15 == 0){
System.out.println("ÒFizzBuzzÓ");
} else if (i%3 == 0){
System.out.println("ÒFizzÓ");
} else if (i % 5 == 0){
System.out.println("ÒBuzzÓ");
}
}
When Java says something cannot be resolved as a variable, it is usually been used outside the scope it was declared or it was not declared at all.In your case, your braceless for-loop is causing the problem.

The operator < is undefined for the argument type(s) boolean, int

I am new to processing and I am having trouble with this. I keep getting an error message for the bolded part of the code below. Is my syntax wrong?
void block(int x, int y, int s, color tinto) {
fill(tinto);
for (int i = 0; i < 3; i++) {
triple(x, y+i*s, s, tinto);
}
if (0 < i < 3 && 6 < i < 9) { // HERE
tinto = 255;
}
else {
tinto = tinto - 200;
}
}
In Java, to check if a variable is in a range you have to divide the statement into two parts, like this:
if (0 < i && i < 3 && 6 < i && i < 9){
}
This specific code will never be true, however, because you're asking for it to be in two different ranges. Perhaps you meant to check for either range?
if (0 < i && i < 3 || 6 < i && i < 9){
}
Note the || or operator instead of the && and operator.
The syntax is not valid, and I think you're expression is wrong anyway. You say i has to be within a range AND within another. I think you mean to write that it could be between one OR the other.
Example of valid syntax: instead of 0 < i < 3, write i > 0 && i < 3.
Try this:
if ( (i > 0 && i < 3) || (i > 6 && i < 9) )
Note that the following (which is what you were trying to do apparently) will never be evaluated to true because it cannot be within both ranges.
if ( (i > 0 && i < 3) && (i > 6 && i < 9) ) // incorrect
This isn't valid java expression. Try:
if (0<i && i<3 && 6<i && i<9){
There are two different problems with this code snippet. First, you have defined the 'i' variable as in "int" inside of the for loop. This instance of 'i' is no longer defined once you exit that for loop -- so the if statement below does not refer to that instance. To overcome this, define 'i' before the for loop...
int i;
for ( i=0; i<3; I++ ) {
...
}
if ( i ...
which brings me to the second error. The syntax "0 < i < 3" is not correct. In c/c++ the operators are executed one at a time ... so in this case the first "<" operator will be evaluated as "0 < i" and the result will be a Boolean (which will always be 'true' in your particular code snippet). But the important point is that the result is a Boolean. Next the code will attempt to evaluate that result with the next part of the statement -- "true < 3", which just doesn't make any sense, and so that receives a compiler error.
In your code snippet, there is no exit to the for loop until the value of i reaches 3, so this second "if" statement is unneeded. But if you did want to test to see whether i was between 1 and 2 (inclusive), then you would have to break those up into individual tests...
if ( 0 < i && i < 3 ...
Lastly ... if the value of i is between 1 and 2 (inclusive), then it cannot also be between 7 and 8 (inclusive) .. therefore the if statement as you coded it will always be false even after we correct the syntax.

Categories

Resources