문제

I have a function of C/C++ code that I wish to convert to Java but am not exactly sure what its trying to due to very little knowledge of the language.

public P unknown(int min1, int max1, int min2, int max2)
{
  this._a = this._a < min1 ? min1 : this._a;
  this._a = this._a > max1 ? max1 : this._a;
  this._b = this._b < min2 ? min2 : this._b;
  this._b = this._b > max2 ? max2 : this._b;
  return this;
}

What I am wondering is why

this._a = this._a

Isn't that redundant? Is the code supposed to do the following in Java?

public P unknown(int min1, int max1, int min2, int max2)
{
  this._a < min1 ? this.a = min1 : this.a = this._a;
  this._a > max1 ? this.a = max1 : this.a = this._a;
  this._b < min2 ? this.b = min2 : this.b = this._b;
  this._b > max2 ? this.b = max2 : this.b = this._b;
  return this;
}
도움이 되었습니까?

해결책

this._a = this._a does not appear as a complete statement anywhere. The expression is part of the statement that contains the ternary operator

this._a = this._a < min1 ? min1 : this._a;

so the statement isnt actually redundant.

Read: The Conditional (or Ternary) Operator (?:)

다른 팁

The ternary operator is basically an if statement built into a single expression;

if X ? do y : else do z

this._a = this._a < min1 ? min1 : this._a;
assign    comparison       then   else

Incidentally the method you are trying to convert is actually already completely valid Java, you shouldn't need to do anything with it! As it happens everything in that method is the same in both languages.

it's not redundant, but just a formatting of the language.

this._a = (this._a < min1) ? min1 : this._a;

means that the program will compare _a with min1, assigning the first value after the ? if true or the latter, if false.

Your java snippet does the same thing

I guess you don't understand the ternary operator correctly. It's not a conditional block of statement(s) but rather a conditional expression.

It's not:

(condition) ? (what to do in case of true) : (what to do otherwise)

but rather

(condition) ? (what the expression evaluates to in case of true) : (what otherw.)

so the ... ? ... : ... part is only a value which is in your program then assigned to a variable.

This code is not doing this._a = this._a, that will be silly. It is using ternary operator. This is the way to read, hope it makes sense to you :

this._a = (this._a < min1 ? min1 : this._a);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top