-4

I have the following statement...

personName[0] = n[y].getName().equals ("Penny") ? personName[0]++ : personName[0];

personName[] is an integer array. getName returns a string. Every time getName is equal to "Penny," I want personName[0] to add one. How should I do this? When I run it, personName[0] does not add one and I don't know why.

2 Answers2

5

Don't try to abuse the conditional operator like this. A plain old if is vastly more readable and concise:

if (n[y].getName().equals ("Penny")) {
  personName[0]++;
}

If you must use a conditional operator, it would be clearer to use +=:

personName[0] += n[y].getName().equals ("Penny") ? 1 : 0;
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
0

If you want just to increment personName[0], wouldn't be better to use just an if? Sometimes, conditional operator is to much for simple problems.

reisdev
  • 3,215
  • 2
  • 17
  • 38
  • It helps the original asker if you can provide with your answer an example of supporting code. In this case, it would be more helpful if you could rework the conditional statement into a plain `if` statement, and explain why it is better than the original code sample provided. – anothermh Apr 29 '18 at 19:00
  • @anothermh, thanks for the explanation! I'll do it next times. – reisdev Apr 29 '18 at 19:04