Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert the following C++ statement to Java?

Tags:

java

c++

I have the following code snippet where 'b' is an integer array, MAX is an integer and an integer 'ans' stores the result. I'm debugging some code and am not very familiar with C++ as I use Java. The C++ code is:

for(i=0; i<MAX; i++)
    ans+=(b[i]!=-1);  

The way I have understood it is as:

for(int i=0;i<MAX;i++)
    if(b[i]!=-1)
        ans+=b[i]; 

However, I get an absurd answer with the logic above. What does the statement really mean?


2 Answers

I think the Java equivalent is

for(int i=0;i<MAX;i++)
   if(b[i]!=-1)
      ans++;

In C++, a true statement evaluates to 1. Java does not do that so you have to explicitly increment ans.

Also, note that if MAX is the length of the array (I don't know if it is or not) you can use a for each loop.

for (int a : b)
    if (a != -1)
        ans++;
like image 151
Paul Boddington Avatar answered Dec 20 '25 09:12

Paul Boddington


for(i=0; i<MAX; i++)
    ans+=(b[i]!=-1);  

C/C++ evaluates this (b[i]!=-1) to either 0 or 1. In java, that evaluates to a boolean value (true or false), and Java does not convert booleans to integers automatically. However would is very easy to do on your own.

e.g.

for(i=0; i<MAX; i++)
    ans+=(b[i]!=-1) ? 1 : 0;  

ought to work just fine.

like image 34
Bill Avatar answered Dec 20 '25 09:12

Bill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!