Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I'm trying to figure out how to do something like:
int test = 1;
int test1 = 10;
if (value = test (though) test1) {
}
I've looked at oracles java operators but could not figure out how to do it.
The construct should check if value is between test and test1.
Can anybody tell me how to do this in Java?
if (value >= test && value <= test1)
{
//doSomething
}
Java does not support chained inequalities, ie test <= value <= test1, so instead you can just use two boolean expressions, connected via the boolean and operator, to get a logically equivalent conditional.
You should try something like with logical and operator
if (value > test && value < test1) {
// do something
}
or add >= to add equals comparison too.
It looks like you are looking for range operator that is common in a lot of programming languages, Java not being one of them, but the condition that you are trying to impose on the range will always be the same. You don't need to check every value in the range, merely the endpoints since it is contiguous:
if( value > test && value < test1 ) {
// do something
}
There is no through op in Java. You can do it with a simple if :
if (value >= test && value <= test1) {
// your code
}
This post begged to be clarified.
If you are checking that value is between test1 and test2 then you need:
if(value >= test && value <= test1){
// do stuff
}
Note that you should remove the = signs if value should be strictly between test and test1.
However, if you are checking that value is one of multiple tests from test0 "through" test10 for instance, then pack those tests in a set and check if value is among them:
import java.util.*;
Set tests = new HashSet();
tests.add(test);
tests.add(test1); // similarly for as many as you need
if(tests.contains(value)){
// do stuff
}
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I have this code...
class Test {
public static void main(String[] args) {
Boolean mySuperBoolean = Boolean.FALSE;
System.out.print("a");
if (mySuperBoolean = Boolean.TRUE) {
System.out.print("b");
}
System.out.print("c");
}
}
I am new to Java, but I knew single equal (=) is used to assign. And double equals (==) is used to check if object is referred to the same location in memory. However, in this case I do not understand how the 'b' is being printed with a single equals, but I understand changing it to a double equals sign will not print it out
if (mySuperBoolean = Boolean.TRUE) will assign Boolean.TRUE to your mySuperBoolean variable and the condition will evaluate to true, hence whatever is inside your if it will always execute
The result of the assignment operator = will be the assigned value. So if (mySuperBoolean = Boolean.TRUE) will always evaluate to true.
Assignment is an expression which resolves to whatever was assigned, in this case(mySuperBoolean = Boolean.TRUE) is an expression which resolves to Boolean.TRUE.
This is really only useful in a few specific situations. One such case is the following idiom:
String line;
while ((line = readLine()) != null) {
//...
}
Or even
i = j = k = 0; // equal to: i = (j = (k = 0))
It's a controversial feature because it allows probable bugs such as yours to compile successfully. To mitigate this, some people will invert the operands (a "yoda condition"):
if (Boolean.TRUE == mySuperBoolean)
This works because if I forget the second equals then the compiler will throw an error because Boolean.TRUE is final and cannot be assigned to.
In essence, what happens here boils down to:
if (Boolean.TRUE) {
System.out.print("b");
}
That assignment puts TRUE into the variable, the variable is boolean, and checked for its current value, end of story.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have two methods, that I believe can be made better way, but can't find this way.
First:
public int calcPow(long num) {
int count = 0;
while(num/2!=0) {
num = num/2;
count++;
}
return count;
}
The second is:
private long findParentNumber(long value) {
for(int bitNum = 0; bitNum < Long.SIZE; bitNum++) {
if((value & (1L << bitNum)) != 0) {
return value ^ (1L << bitNum);
}
}
throw new RuntimeException("No parent number found");
}
I believe, there are ways to do the same without loops. Can you help?
Cheers!
For the second one, you're unsetting the lowest set bit. There's a relatively well known bithack to do that, though only relatively because it seems that bithacks in general are not well known.
Anyway, it's
return x & (x - 1);
The logic here is that in x - 1, there's a borrow running through the lowest zeroes until it hits the lowest 1-bit, which it unsets. The lowest zeroes are left set, they are then removed by ANDing it with the original number.
You can write the first one in terms of numberOfLeadingZeros, which would be more obviously correct than floating point hacks which always make you think about how accurate they might be (and in any case they're slow, you might be better off with the loop).
Edit: for completeness, that would be 63 - numberOfLeadingZeros(x), it differs from your definition at x = 0 but that's a bad input anyway.
Try this for the first one.
public int calcPow(long num) {
if (num == 0) return 0;
if (num < 0) num = -num;
return Long.numberOfTrailingZeros(Long.highestOneBit(num));
}
Or this suggested by harold
public int calcPow(long num) {
return num == 0 ? 0
: 63 - Long.numberOfLeadingZeros(Math.abs(num));
}
For the first one, you can use the Math.log method that already exists:
public static int log2(long number) {
return (int) Math.floor(Math.log(number) / Math.log(2));
}
or this faster function suggested by saka1029:
public static int log2(long number) {
return number == 0? 0: Long.numberOfTrailingZeros(Long.highestOneBit((number < 0)? number * -1: number));
}
As you can see I also changed the method to static, since I see no point in having to use an Object to get a log when no object is involved. And secondly I changed the names into something more fitting.
For the second one you can use the bit-wise check operator &:
public static long removeSmallBit(long value) {
return value & (value - 1);
}
Essentially you are removing the smallest bit from the variable, and return that number after you change that bit to 0. And as you can see again I made the method static and changed the name. 2nd answered inspired by this answer submitted by harold
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I am trying to get a Save button to enable/disable based on if the EditTexts actually change, but my string comparison is not working at all.
public void afterTextChanged(Editable editable) {
String newSet = editable.toString();
newSet = newSet.trim();
if(!newSet.equals(ip) || !newSet.equals(port) || !newSet.equals(username) || !newSet.equals(password)){
saveButton.setEnabled(true);
}else{
saveButton.setEnabled(false);
}
}
It keeps telling me the strings are different even though they aren't. Even when I print it out I get exactly the same String back.
Can anyone help me?
Thanks
Probably you want && instead of ||:
public void afterTextChanged(Editable editable) {
String newSet = editable.toString().trim();
saveButton.setEnabled(!newSet.equals(ip) &&
!newSet.equals(port) &&
!newSet.equals(username) &&
!newSet.equals(password));
}
enable saveButton if newSet is not a ip, port, username or password
You should write it like that, way easier to read :
if (!Arrays.asList(ip, port, username, password).contains(newSet))
{
saveButton.setEnabled(true);
}
else
{
saveButton.setEnabled(false);
}
Or :
saveButton.setEnabled(!Arrays.asList(ip, port, username, password).contains(newSet));
newSet can't be equal to all four of these Strings, unless all 4 are equal to each other. Therefore the condition will most likely return false.
If you require that newSet be equal to either one of those 4 Strings, the correct condition would be :
if(!(newSet.equals(ip) || newSet.equals(port) || newSet.equals(username) || newSet.equals(password)))
replace || with &&
if(!newSet.equals(ip) && !newSet.equals(port) && !newSet.equals(username) && !newSet.equals(password))
Reason :
OR(||) If any condition get satisfied it will enter inside the loop.
AND(&&) If all conditions get satisfied then and then only it will enter inside the loop.
In your case you need to satisfy all the conditions, that's why use and operator instead of or operator.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have a task to write a simple Java program:
I have two integers a and b. If a>10 and b<10 then it should print out "balanced" and if not then print out "unbalanced"
I know how to make this with 1 variable, but i don't have clue how to make it with 2.
Here is something I have tried:
public static void main(String args[]) {
int a = 1;
int b = 15;
if (a > 10 && b <= 10)
{
System.out.println("balanced");
}
else
{
System.out.println("unbalanced);
}
}
Your code not even compile since there is syntax error. You can make your mistake correct as follows.
int a = 1;
int b = 15;
if (a > 10 & b <= 10) { // why <= by reading your question it should <
System.out.println("balanced");
} else {
System.out.println("unbalanced");
}
Now out put is unbalanced.
Now let's review your code. you have use &(non short circuit) and here. That's not good since always non short circuit operands evaluate both side of the expression.
So you should use && (short circuit)
int a = 1;
int b = 15;
if (a > 10 && b <= 10) {
System.out.println("balanced");
} else {
System.out.println("unbalanced");
}
What's wrong with non short circuit?
Consider following logic.
if(name!=null&name.getFirstName()=="same"){ // Now both side evaluate
}
what happen name==null?, name.getFirstName() will give you NullPointerException. If you use && short circuit you are same from this NPE
if(name!=null&&name.getFirstName()=="same"){ // if first case false not
evaluate second
}
Use && instead of & so that it does a logical and not a bitwise one.
You will find it clearer to read if you put brackets around (a > 10) && (b <= 10) as well.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
why cannot I check if a place in array is empty ?
I got this wrong message:
The operator == is undefined for the argument type(s) int, null"
on the marked line
private static int findNr(int[] trans)
{
int emptyPlace=0;
for (int i=0; i<trans.Length -1;i++)
{
--> if( trans[i] = null) <--
return emptyPlace = trans[i];
}
return emptyPlace;
}
You can not compare primitive data type for null. int is primitive data type.
You have to do
if( trans[i] == null)
instead of
if( trans[i] = null)
^-----------Mistake
Anyway in which language you have written the code?
You try to assign null to the array element at position i
To check if the element is null you have to do:
if(trans[i] == null)
{
...
}
but this expression doesn't make any sense since an int can never be null (unless its a nullable int (int?)) so the condition will always be false
Primitive cannot be checked with the null. So for particular primitive types use their default value to check.
i.e for int default value is 0 and for
double default value is 0.0 etc.
So check as:
if(intr[i]==0){
//some logic
}
if( trans[i] = null)
In the above line your are using assignment operator = in place of comparison operator ==. If condition expects the final value after computation to be of the type boolean. Hence you get the error.
Also your trans[i] is an primitive int value which cannot be compared to a null. (Only objects can be null in java)
The assignment operator = will only work in case of boolean variables, something like this:
boolean flag = false;
if(flag=true) {
// this condition will be true
}
First, you mispelled the == comparison. Should be:
if (trans[i] == null)
Second, the above doesn't works. Primitive values can never be null, when you declare any int variable, it's 0 by default.
Thats why:
int[] v = new int[3];
for (int i = 0; i < v.length; i++)
System.out.println(v[i]);
Outputs this:
0
0
0
You should either work with Integer objects array or review your logic.
1- You have forgot '=' ---> if (trans[i] == null)
2- You can't compare primitive value (int) with null