user663724
user663724

Reputation:

Java : with respect to Ternary Operator for this requirement

<Student>
<number>122</number>
<CVF>PG</CVF>
</Student>

class Student 
{
char grade 
}

Now , i need to set the grade value for the Student Object above by parsing the XML Above

This CVF Element in XML can have two values either PG or MQ

As per the business , If it is PG then its value should be 1 or else 0

I defined in this way .

Student.grade = (attribute.getValue().toString()=="PG"?'1' : '0');

Please let me know if any better code will be suitable for the above requirement ??

Upvotes: 0

Views: 115

Answers (3)

Rob N
Rob N

Reputation: 16409

A few points:

  1. I don't know what XML library you are using, but <CVF> is not an attribute. But let's assume attribute.getValue() is correct.
  2. If attribute.getValue() returns a string, there is no reason to call toString().
  3. Use equals() not == when comparing Strings, unless you know they are interned.
  4. You don't write Student.grade unless it's a static field. You have a variable of type Student with a name, say s, and then you can say s.grade.
  5. If the input has not been validated, you might want to drop the ternary operator and do something like:


Student s = ...
String val = attribute.getValue().toString();
if ("PG".equals(val)) {
    s.grade = '1';
}
else if ("MQ".equals(val)) {
    s.grade = '0';
}
else {
    throw new RuntimeException("illegal value for CVF: " + val);
}

Upvotes: 1

Sajan Chandran
Sajan Chandran

Reputation: 11487

Dont compare Strings with "=". Its always better to do this instead.

Student.grade = ("PG".equals(attribute.getValue().toString()))?'1' : '0';

Upvotes: 0

kosa
kosa

Reputation: 66637

Assuming grade defined as char.

Student.grade = ("PG".equals(attribute.getValue().toString())?'1' : '0');

Upvotes: 0

Related Questions