This is some of my current code:
Class usedCoords contains:
public List<Integer> USEDX = new ArrayList<Integer>();
main function contains:
if(fX % gridX == 0 && fZ % gridZ == 0 && ALPHA != 0 && usedcoords.USEDX == fX) { }
Note I also done: usedCoords usedcoords = new usedCoords();, that is why I named it usedcoords.
My main task is that I want to make the usedcoords.USEDX == fX possible. Currently I will get an error because fX is an integer. USEDX has integers as well so how do check that the any integer in USEDX is equal to fX?
Thanks in advance.
Use List#contains() -- and it's more readable and conventional not to have variable names start with an uppercase unless they are constants:
if (fX % gridX == 0 && fZ % gridZ == 0 && alpha != 0 && usedcoords.usedX.contains(fX)) {
...
}
The int variable fX will be automatically boxed into the Integer type by the compiler.
USEDX has integers as well so how do check that the any integer in USEDX is equal to fX?
By calling List.contains(Object) which returns true if this list contains the specified element. Something like,
if (USEDX.contains(fx)) {
// ...
}
For efficiency-sake, you may use Hashtable<Integer> instead of List because it requires O(1) (constant) time to search for a value.
Related
I'm attempting the below:
if(p1S > p2S && p3S)
}
But the IDE doesn't like the && here.
So, how would I compare these 3 ints to find the one with the highest value, thus moving forward.
Aka: If Int 1 is greater than int 2, and int 3, then do this. . .
I suspect I just don't know the syntax well enough just yet (I've only just started college for CS).
Is this what you want?
if(p1S > p2S && p1S > p3S)
}
The reason the previous code didn't work is that the first part
if(p1S > p2S && p3S)
}
evaluates to:
if(boolean && p3S)
}
And you can't do an && between a boolean and an int.
String userGuessParameters = "a,b";
while (!Character.isDigit(userGuessParameters.charAt(0)) ||
!Character.isDigit(userGuessParameters.charAt(2)) ||
userGuessParameters.length() != 3 ||
(int)(userGuessParameters.charAt(0)) >= parameters[0] ||
(int)(userGuessParameters.charAt(2)) >= parameters[1]) {
System.out.print("Mida kaevame (rida, veerg): ");
userGuessParameters = userInput.nextLine();
userGuessParameters = userGuessParameters.replaceAll(" ", "");
}
I'm trying to check if all the required conditions are fulfilled in the while loop. parameters is what user entered in array form. Let's assume parameters = [4, 4] (Parameters is used to create a 4x4 map).
I need userGuessParameters to be:
Numbers
Length equal to 3 (the input looks like this: 2,2 when the spaces are removed)
Smaller than the biggest coordinate (which is 3,3)
But for some reason, the loop never exits. I'm almost certain it is because of the last two conditions in the while loop, but I can't find the mistake.
You are using the logical OR operator when you should be using AND (you want all the conditions to be met, not just at least one of them).
Use the java notation for AND which is &&:
(!Character.isDigit(userGuessParameters.charAt(0)) &&
!Character.isDigit(userGuessParameters.charAt(2)) &&
userGuessParameters.length() != 3 &&
(int)(userGuessParameters.charAt(0)) >= parameters[0] &&
(int)(userGuessParameters.charAt(2)) >= parameters[1])
Try to use && instead of || like this:
while (!Character.isDigit(userGuessParameters.charAt(0)) && !Character.isDigit(userGuessParameters.charAt(2))
&& userGuessParameters.length() != 3 && (int)(userGuessParameters.charAt(0)) >= parameters[0]
&& (int)(userGuessParameters.charAt(2)) >= parameters[1]) {
This question already has answers here:
Does Java evaluate remaining conditions after boolean result is known?
(7 answers)
Closed 7 years ago.
Does java calculate the second condition in ( test1 || test2 ) if the first one is true ?
I use Optional and I have something like that :
if (!opt.isPresent() || opt.get() == currentPlayer.getSelectedRegion())
and there will be a problem if the first test is true and java compute the second test.
If first condition is true second condition is not evaluated.
If first condition is false also second condition is evaluated.
That's why you can write a code like the following without a NullPointerException
if (str == null || str.length() == 0) {
// do something
}
The operator | (instead of || ) will evaluated both conditions
So the code
if (str == null | str.length() == 0) {
// do something
}
can generate a NullPointerException if str is null
Does java calculate the second condition in ( test1 || test2 ) if the first one is true ?
No. Boolean or will short-circuit, the first true is sufficient to make the expression true. No further conditions will be evaluated after that.
If you use the || and &&, rather than the | and &, Java will not bother to evaluate the right-hand operand.
No, java short-cut operators, the second argument is not evaluated if the first is. Ore more formal:
for x || y, y is only evaluated if x is false; and
for x && y, x is only evaluated if y is true.
This will increase performance and can be both useful and tricky:
usefull: to prevent you from doing things such that an error is thrown. The most typical example is the null check:
if(x != null && x.someTest())
this will prevent .someTest being called if x is null.
tricky: the problematic aspect can be if you call a method that does not only return something, but changes state as well. For instance:
public class Foo {
private int checked = 0;
bool someCondition () {
return (checked % 2) == 0;
}
bool neverChecked () {
checked++;
return checked == 1;
}
}
if you now call:
if(foo.someCondition() || foo.neverChecked());
this is one of the main reasons it is adviseable to keep "getters" (thinks that calculate things of an object), and "setters" (things that modify the state of an object), clearly separated. From the moment you start mixing, one can get complicated behavior in some circumstances.
it can be the intention that you always increment checked, but it will only if .someCondition happens to be false.
That's my while loop, and the question is, how can i get a true condition?
s and t are Integer variables
while (s<=t && s>=t && s!=t )
EDIT
tl;dr the original question stated:
s and t are int variables (and OP commented they are not Integer variables)
Never!
s and t are int variables, so when s == t the third operand will fail, when s != t one of the first two operands will fail.
Possible, but unlikely, if they are declared as volatile int s, t; in a multi-threaded application.
EDIT
Question has been modified. Now s and t are Integer variables, which makes the answers referring to Integer objects more relevant.
By boxing the primitive value in an object:
Integer s = new Integer(5);
Integer t = new Integer(5);
boolean rslt = (s <= t && s >= t && s != t);
System.out.println("Result = " + rslt);
The rslt boolean here will indeed evaluate to true.
However, the following would return false:
s <= t && s >= t && !s.equals(t)
it is because in Java, for objects, == means that it is indeed the same instance, while equals is left up to be implemented by every class and typically means that the core values of the compared objects are the same -- while not necessarily being the same class instance (AKA object). The > and < for boxed primitives are evaluated agaist the primitive value, however == is checking the object identity.
It actually is possible:
public class EqualsTest
{
public static void main(String[] args)
{
Integer x = new Integer(Integer.parseInt(args[0]));
Integer y = new Integer(Integer.parseInt(args[1]));
if(x <= y && y <= x && y !=x)
{
System.out.println("equal");
}
else
{
System.out.println("not equal");
}
}
}
Compiling this and running it with two equal integer arguments produces:
$ java EqualsTest 5 5
equal
The reason that this works is due to autoboxing and the fact that, for objects, == only checks whether or not the references are the same (which, in the case above, they are not).
Never man, no way.
s<=t && s>=t returns true if s == t, and s == t && s != t returns false forever.
You cant the only way first two conditions result true is when s is equal to t and the third conditions negates this fact.
Hence i dont think its possible
If the two values are accessible by multiple threads (either static, or members variables of an object shared between multiple threads), you could do this:
Thread 1:
s = 1; // 1
t = 1; // 2
t = 2; // 5
Thread 2:
This is equivalent to your expression but easier to label.
boolean result = s <= t; // 3
if(result) {
result = s >= t; // 4
}
if(result) {
result = s != t; // 6
}
Assuming everything happens in the order given by the commented numbers, then at the end of thread 2's code, result will be true.
So, thread 1 sets s and t to be equal, then thread 2 checks that they're equal, then thread 1 sets them to be not equal, then thread 2 checks that they're not equal.
There are more complicated situations where this could be true, but this is the simplest one I could think of.
If i have the following if statement
if ( (row != -1) && (array[row][col] != 10) ) {
....
}
Where row is an int value and array is an int[][] object.
My question is, if this will throw an exception if row = -1 as the array won't have a -1 field, so out of bounds exception? Or will it stop at the first part of the if, the (row!=-1) and because that is false, it will ignore the rest?
Or to be sure it doesn't throw exception, i should separate the above if statement into two?
(Pls, don't tell me to check this out for my self :) I'm asking here 'cause i wanna ask a followup question as well ...)
It will stop safely before throwing an exception
The && is a short-circuiting boolean operator, which means that it will stop execution of the expression as soon as one part returns false (since this means that the entire expression must be false).
Note that it also guaranteed to evaluate the parts of the expression in order, so it is safe to use in situations such as these.
It will not throw an exception. However, if row is < -1 (-2 for example), then you're going to run into problems.
It will stop at the first part of the if. Java uses short circuite evaluation.
No, It wont. the compiler will not check the second expression if the first expression is false... That is why && is called "short circuit" operator...
Called a short-circuit evaluation via the && and if the row check fails, there is no point in continuing evaluation.
Most programming languages short-circuit the test when the first expression returns false for an AND test and true for an OR test. In your case, the AND test will be short-circuited and no exception will occur.
Many programming languages have short-circuit evaluation for logical operators.
In a statement such as A and B, the language will evaluate A first. If A is false, then the entire expression is false; it doesn't matter whether B is true or false.
In your case, when row is equal to -1, row != -1 will be false, and the short-circui the array expression won't be evaluated.
Also, your second question about the behavior of the array index is entirely language-dependent. In C, array[n] means *(array + n). In python, array[-1] gives you the last item in the array. In C++, you might have an array with an overloaded [] operator that accepts negative indexes as well. In Java, you'll get an ArrayIndexOutOfBoundsException.
Also, you might need something like the following (or just use a try/catch).
boolean isItSafe(int[][] a, int x, int y) {
boolean isSafe = true;
if (a == null || a.length == 0 || x >= a.length || x < 0 || y < 0 || y >= a[0].length ) {
isSafe = false;
}
return isSafe;
}