Trying to convert a bunch of C++ codes into Java - if statement - java

i was trying to write some C++ codes into java, now i have writter following code into java but it is throwing errors!
if(ShapeNotFound && xd*yd - nPixel[k] < xd+yd) // Condition for RECTANGLE
{
System.out.print("\n "+in+" \t Rectangle \n");
fileWriter3.write("\n "+in+" \t Rectangle \n");
Shape[k] = 2;
ShapeNotFound = 0;
}
I am getting following error :
The operator && is undefined for the argument type(s) int, boolean
Please help, tell me how to write the above if condition correctly in java

C and C++ both assume that for integers 0 is false and all other values are true.
Java does not make the same assumption so you need to add a check for int!=0 into the expression i.e.:
if((ShapeNotFound!=0) && (xd*yd - nPixel[k] < xd+yd))
Or alternatively your ShapeNotFound variable should be of type boolean not int.
It would be worth converting variable names etc to Java style guidelines as well.

Java can not convert int into boolean automatically.

It looks like ShapeNotFound is an integer, but you're implicitly treating it like a boolean (true or false). Java only likes genuinely boolean expressions, so you'll need to change the condition to something like this:
if (ShapeNotFound != 0 && xd*yd - nPixel[k] < xd+yd)
For readability, I'd suggest putting some brackets round each part of the condition. That's an issue of personal preference though.

Related

Treating an integer as a boolean in Java

I'm working on updating an old Java application to work on modern operating systems and I've run into an error that I can't figure out. I don't have much experience with Java but from what I've read, you can't store boolean values in an integer (1 or 0) like in C++.
Here's the bit of code where the error is:
public static double a(cr paramcr, int paramInt) {
double d = 0.0D;
int i = ++b;
if (b <= l.length()) {
if (paramInt < 0) {
int j = b; // <----------- defined again as an integer.
d = e();
if (e == true && d >= h && d + f - g >= 1.0D && d + f - g <= d) {
String str1 = String.valueOf((int)d);
d = d + f - g;
String str2 = String.valueOf((int)d);
l = a(j, l, str1, str2, i);
} else if (j == false) { // <---------------------------- error
if (((d < 1.0D || d > d) ? false : true) == false)
c = 7;
}
With error message:
The operator == is undefined for the argument type(s) int, boolean
The variable j is defined as a static boolean at the top of the program, but later redefined as an integer inside of this 'a' class. I notice that there are other integer variables being used to compare to true and false statements in this class, but they are all being compared to some condition in order to get a true or false result. That's obviously not the case here, and my problem is that I can't think of a way that this program would have ever functioned in the past if this is how it was written. Any ideas as to why this could be or suggestions on my next move?
It doesn't help that none of this has any documentation or intuitive variable names.
In Java you cannot treat an int as a boolean. Period.
I was sent some files that I was told contained the source code. It did not. I was then told to decompile it.
What you are apparently looking at is some code that has been decompiled from a ".class" file. Decompilation is NOT guaranteed to produce valid (compilable) Java source code. And in this case, it appears that it hasn't. Indeed, there are clues in that code that imply that the original bytecodes were obfuscated ... to deliberately make it hard for the decompiler to generate readable / valid Java source code.
(The problem is that the same bytecodes are used dealing with boolean and integer types up to int. In this case, the decompiler has assumed that the local variable is an int, and not been able to figure out that its assumption was incorrect. A better decompiler might be able to figure it out ...)
So what you will need to do is figure out how to modify that (not-really-Java) code to make it 1) compilable, and 2) do the correct thing1.
It doesn't help that none of this has any documentation or intuitive variable names.
Well ... that what happens when you try to use decompiled code. All local variable names and comments (including javadocs) are discarded by the compiler, and the decompiler has no way to reconstruct them.
The alternative is to go back to the people who were supposed to give you the source code and ask them to provide it to you ... for real!
1 - This assumes that you can figure out what this method is really supposed to be doing. I don't think we can help you with that. For a start, it would probably be necessary to read the disassembled bytecodes to figure out what the code really does.

Throw Expected After This Token Error

When I run my code, it gives me an error that says, "Syntax error on token "{", throw expected after this token." The error is on line 7's code.
class WhileLoopTest {
public static void main(String[] args){
apple = 0;
while (apple = 0) {
(int)(Math.random( )*(60) + 5);
return;
}
}
}
on the line while (apple = 0) you are setting the variable instead of declaring it. The while loop expects that you pass it a boolean. You are probably trying to use the comparison equals ==. The full line should read while (apple == 0).
First , you need to define a type for your variable apple because Java is statically type
apple = 0;
Read more About Statically typed vs Dynamically typed
change to
int apple = 0;
Second, (int)(Math.random( )*(60) + 5); is not statement so you need to either print the value or return it
Third, while (apple = 0) { is wrong because compiler looking for Boolean expression
while(Boolean_expression)
{
//Statements
}
change to while (apple == 0 ) {
You need to add an extra equals sign to the condition within the while statement (at the moment you are assigning the value of 0 to apple, instead of texting if it is equal), so it looks like this
while(apple == 0){
Pleas note that the while loop has no function at all, since you are returning within the loop. This will stop your program execution as you are returning from the main method. The computation of a random number doesn't serve a purpose here as you aren't assigning a variable to it or printing it.
Also, you are not defining a type for the apple variable. Try making it of type int.
int apple = 0;
I suggest that you look up some tutorials on java as you seem to misunderstand several concepts within the language.

Weird corruption of Boolean Array in Java

This might sound weird but I am struggling with this bug for past 2 days.
I have a boolean array in java that is initialised using a Random boolean generator.
After that the boolean array is acted upon by a function in C (called using JNI) and the modified boolean array is returned to java. When I hand over the boolean array to C, it is converted to unsigned char and converted back to jbooleanArray before being handed back to java.
Now I run the following code (there is a for loop over i):
if(chosen_packet[i] == false)
{
pkt.first[i] = 0;
System.out.print(chosen_packet[i]);
}
if(chosen_packet[i] == true)
{
pkt.first[i] = 1;
System.out.print(chosen_packet[i]);
}
The problem is that sometimes when chosen_packet[i] is true it still does not enter the second if condition. This happens sometimes and sometimes the code works just fine. When I print chosen_packet[i] in such a case it is printed as true yet it does not enter the second if condition. What could be the possible reason for this seeming corruption of the boolean array ?
EDIT: This is how I convert the boolean array to unsigned char in C:
jboolean *element = (*env)->GetBooleanArrayElements(env,chosen_packet,0);
for(j = 0; j < sz; j++)
src_pkt[j] = (unsigned char)element[j];
This src_pkt is acted upon and then I convert it back to jboolean .
EDIT2: This is how I convert the unsigned char array back to jboolean:
jbooleanArray arr = (*env)->NewBooleanArray(env,sz);
(*env)->SetBooleanArrayRegion(env,arr,0,sz,src_pkts);
(*env)->DeleteLocalRef(env,arr);
It's normal that if the boolean is true it does not enter in the first if since you are checking for it to be false in its condition.
Your code can be simplified to (you should use if/else instead of two if checking for the different conditions).
if (chosen_packet[i]) {
pkt.first[i] = 1;
} else {
pkt.first[i] = 0;
}
System.out.print(chosen_packet[i]);
or even
pkt.first[i] = chosen_packet[i] ? 1 : 0;
System.out.print(chosen_packet[i]);
Edit
If your program does not enter the second if, it means that the the var chosen_packet[i] is not true, you could use a debugger to verify what is the real value.
As stated by fredcrs, are you sure that chosen_packet[i] is of type boolean?
Java boolean is usually implemented as single byte. So it is possible that there is a bug in your C code that causes the boolean to be neither true nor false. In that case you may encounter undefined behavior.
Note that simply casting unsigned char to jboolean as in(jboolean) src_pkt[j] does not normalize it. You have to use src_pkt[j] ? JNI_TRUE : JNI_FALSE.
Still I believe you have to post more of relevant parts of your JNI code.

if statement with integers [duplicate]

This question already has answers here:
Why does my if condition not accept an integer in java?
(7 answers)
Closed 3 years ago.
I'm new at Java. I'm looking for some help with homework. I wont post the full code I was doing that originally but I dont think it will help me learn it.
I have a program working with classes. I have a class that will validate a selection and a class that has my setters and getters and a class that the professor coded with the IO for the program (it's an addres book)
I have a statement in my main like this that says
//create new scanner
Scanner ip = new Scanner(System.in);
System.out.println();
int menuNumber = Validator.getInt(ip, "Enter menu number: ", 1, 3);
if (menuNumber = 1)
{
//print address book
}
else if (menuNumber = 2)
{
// get input from user
}
else
{
Exit
}
If you look at my if statement if (menuNumber = 1) I get a red line that tells me I cannot convert an int to boolean. I thought the answer was if (menuNumber.equals(1)) but that also gave me a similar error.
I'm not 100% on what I can do to fix it so I wanted to ask for help. Do I need to convert my entry to a string? Right now my validator looks something like:
if (int < 1)
print "Error entry must be 1, 2 or 3)
else if (int > 3)
print "error entry must 1, 2, or 3)
else
print "invalid entry"
If I convert my main to a string instead of an int wont I have to change this all up as well?
Thanks again for helping me I haven't been diong that great and I want to get a good chunk of the assignment knocked out.
if (menuNumber = 1)
should be
if (menuNumber == 1)
The former assigns the value 1 to menuNumber, the latter tests if menuNumber is equal to 1.
The reason you get cannot convert an int to boolean is that Java expects a boolean in the if(...) construct - but menuNumber is an int. The expression menuNumber == 1 returns a boolean, which is what is needed.
It's a common mix-up in various languages. I think you can set the Java compiler to warn you of other likely cases of this error.
A trick used in some languages is to do the comparison the other way round: (1 == menuNumber) so that if you accidentally type = you will get a compiler error rather than a silent bug.
This is known as a Yoda Condition.
In Java, a similar trick can be used if you are comparing objects using the .equals() method (not ==), and one of them could be null:
if(myString.equals("abc"))
may produce a NullPointerException if myString is null. But:
if("abc".equals(myString))
will cope, and will just return false if myString is null.
I get a red line that tells me I cannot convert an int to boolean.
Thats because = is an assignment operator. What you need to use is == operator.
A single equal sign is assignment: you assign value to a variable this way. use two equal signs (==) for comparison:
if ($menuNumber = 1) {
Update: forgot dollar sign: $menuNumber

How do I transfer this c ++ for loop into java for loop

I am a newbie C++ and I want to convert this line of for loop code into java version
for(;diff;diff++){
do something here
}
diff is an integer type variable.
Thanks in advance.
The issue is that C allows an implicit conversion from int to boolean for the termination condition whereas Java doesn't. Try
for(; diff != 0; diff++)
{
which should be equivalent.
In Java, unlike in C++, an integer is not automatically translated to a boolean expression. You have to write it like this in Java:
for ( ; diff != 0; diff++) {
// do something here
}

Categories

Resources