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.
Related
This question already has answers here:
"Comparison method violates its general contract!"
(13 answers)
Closed 1 year ago.
I have defined a Comparator using the ordering wrapper. Could you explain why does this code throw an exception, "Comparison method violates its general contract!"? I would really appreciate it if you could tell me how to fix it.
Ordering<Foo> order = new Ordering<Foo>() {
#Override
public int compare(Foo left, Foo right) {
return getCompare(orderMap, left.getItemId(), right.getItemId());
}
};
Collections.sort(Foos, order);
getCompare :
private int getCompare(Map<Long, Integer> orderMap, Long leftId, Long rightId) {
int indexLeft = orderMap.get(leftId) == null ? -1 : orderMap.get(leftId);
int indexRight = orderMap.get(leftId) == null ? -1 : orderMap.get(rightId);
if (indexLeft < 0 || indexRight < 0) {
return 1;
}
return Integer.compare(indexLeft, indexRight);
}
This is the contract:
If `a.compare(b) is X, and b.compare(c) is X, then a.compare(c) must also be X, whether X is negative, or positive, or zero.
If a.compare(b) is X, then b.compare(a) must be -X: 0 remains 0, -1 turns to +1, etc.
a.compare(a) must be 0.
That's it. Your compare method breaks this in many, many ways. For example, your second line has a bug in it(surely that'd be orderMap.get(rightId) == null, you can clean that up using getOrDefault instead), if either index is not found or less than 0, your code always returns 1, which breaks the rule (a.compare(b), where a is not in the map, returns 1, and b.compare(a) would also return 1. It needs to return a negative number instead).
You're going to have to come up with a rule for what happens if one of these is not in the map. If your code is written with the assumption it can't happen, well, it is - throw an exception when your assumption doesn't hold so you can investigate why your assumption (that all provided left/rightIds are always in the map and always non-negative). As written, your code straight up asplodes in a nasty way if that happens - that's what exceptions are for. Explode in an easily debuggable way.
If that was the intent, you're going to have to make up some rules. For example: If a is in the map but b is not, then a is always higher than b. That means if (indexLeft < 0 && indexRight >= 0) return -1 and also if (indexLeft >= 0 && indexRight < 0) return +1;, in order to stick to the rules. That leaves the question: What if neither is in. You can either choose that there is then no way to order them (Return 0), but do know that means you can't put more than once such item in a TreeMap or TreeSet - but sorting a list, that's fine. Individually not-comparables are allowed, and they'll end up clumped together in an arbitrary order. That doesn't break the rules.
I'm fairly new to programming and I started to write some basic codes. I tried to create an algorithm that found every position of the character you wanted in a string. If I were to enter "helllo" as a string and wanted to search for the character l, it would output 2, 3 and 4. The code worked fine until I tried to trick the code a bit to change something. To do so, I first removed the termination condition in the "for loop" and instead added an if statement during the loop to break it. I spent about 2h on the error that occurred after and I still can't find out what's happening.
Here's the code and the output it gives me. (I know my code is a mess and not properly optimized, but right now I would just like to know what is happening. I'll rearrange it later if I get it to work. thank you^-^.)
When I run the code, instead of displaying as it should, "7, 8, 9, 10"(it searches for the character ^ in the string Oioriew^^^^) it outputs "7-1,8,9,10". To fix it, I can simply insert the termination condition in the loop again, which was, "pow != -1" but at this point, I really want to know why it happens.
public class Tests {
static void zeMethod(String mainString,char charToFind) {
int a = 0;
String b, c;
char chartToConvert;
c = "";
b = "";
for (int pow = mainString.indexOf(charToFind);
; // *the condition was here.*
pow = mainString.indexOf(charToFind, pow + 1)) {
a++;
if (a == 1){
System.out.println("String: "+mainString);
System.out.println("il y a un "+charToFind+" à la/aux position(s)");
}
if (a == 1){
System.out.print(pow);
}
if (a%2 == 0 && pow != -1) {
c = b+", "+pow;
}
if (a%2 != 0 && a != 1 && pow != -1) {
b = c+", "+pow;
}
if (pow == -1){
System.out.print(pow);
break;
}
//*end of loop*
}
if (a%2 != 0){
System.out.println(c);
}
else {
System.out.println(b);
}
}
public static void main(String[] args){
String string = "Oioriew^^^^";
char chara = '^';
zeMethod(string, chara);
}
}
I'm sorry if my question is a bit incoherent or not properly asked. This is my first time on the site and English isn't my mother language. Thank you for your time!
Edit:
I know the question wasn't clear at first, but what I meant is, why does pow become -1 after the second iteration of the loop. Also, why does the break after the System.out.print(pow); doesn't make it leave the loop. (I'm looking how to make a debugger work atm too.)
[...] instead of displaying as it should, "7, 8, 9, 10" [...] it outputs "7-1,8,9,10 [...] I really want to know why it happens
Sounds like you're asking why it prints -1, which happens because you explicitly asked it to:
if (pow == -1){
System.out.print(pow);
break;
}
If pow is -1 then print pow (aka -1) and exit the loop.
UPDATE
As for why the order of the output, use a debugger and step through the code one statement at a time, and you'll see.
But, lets see: We can agree that loop will iterate with pow having these numbers in this order: 7, 8, 9, 10, -1
Why does it print 7 first?
Because you have this code inside the loop:
a++;
if (a == 1){
System.out.print(pow);
}
Why does it print -1 next?
Because there are no other print statements inside the loop, which would be a lot more apparent if you indented the code correctly, i.e. indented the content of the loop.
Why does it print 8,9,10 last?
Because you print the content of b or c after the loop, and that is the content of whichever one of them is being printed.
Note that first value (-7) is not added to b, because you explicitly exclude it in the if statement.
I'm all good, thank you all for your time and Andreas, for the debugger option. It's a must-have for anyone programming. I don't know how I didn't see this earlier, but to break, it had to become -1 and since I had to break before I could print my answer, -1 was first.
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.
I really don't know what should be the title of this question, spent 10 minutes but this is the best I came up with.
The real question is very basic and I think I know the answer. But still, like the operator condition ? true-statement : false-statement, is there any shortcut of this kind of if statement?
if(intA == -1 || intB == -1 || intC == -1 || intD == -1 || intE == -1)
Suggestion: Something like this could be added in Java:
if((intA || intB || intC || intD || intE) == -1)
No.. There isn't. These are different variables with different values.
Suggestion: you can consider the all these variable necessary or not. If all these variables necessary there will be no way to simplify.
You should use lists for this purpose.
For ex.
You can implement function
findFirstEquals(List, Int)
which iterate through the list, search for first element that equals to second parameter and returns true if found.
In this case your if would be like following
intList = ArrayList<Int>()
// put 5, 6, 7,8 etc...
if findFirstEquals(intList, -1) ...
Afaik, there is no real shortcut syntax for this. Probably, you could do some tricks with logical and/or to achieve this, but I would not recommend to do so as it would be harder to read:
if (((intA | intB | intC) & -1) == -1)
You could still add those ints to an collection, and check if -1 is contained in that collection.
Fun fact: In Python, there is syntactic sugar for comparing a variable with 2 values; you can write 2 < a < 3, which would not be possible in Java. But personally, I do not know a language where syntactic sugar for what you are asking for exists.
You can use Switch() statement to make it more easy like below
public void myMethod(int intValue)
{
switch (intValue) {
case -1: //Your logic here ;
break;
case 1 : //Another condition
break;
default: //Default behaviour;
break;
}
}
Call method myMethod(yourValue) and passed your value to it.
Passed your integer value to switch it will handle it as per value you have passed.
May this will help you.
ok these binary trees kinda drive me crazy now. I made a method to get the number of nodes in a tree but the result not correct. There is always one node missing. Any ideas? Help would be appreciated since I don't want to become a tree hater :)
public int size() {
if (this == null) {
return 0;
} else {
return 1 + (right != null ? right.size() : 0)
+ (left != null ? left.size() : 0);
}
}
First of all the if(this==null) is completely useless and can be removed completely as you are calling a method on this so it is therefore not null.
Then, can you provide some input and output data as well as expected result ? We can only make assumptions here and the code seems legit.