screechOwl
screechOwl

Reputation: 28129

Java if statement not being fulfilled

I am a bit rusty on my Java. I have an array with several values one of which is used in an if statement.

It's a single character I'm checking and the fact that it's not working leads me to believe it may be a whitespace issue. The data is coming in from a mysql database and I already tried using trim() on the query to get rid of any whitespaces but no luck.

Here's the code:

  Payoff payoff=new PlainVanillaPayoff(Option.Type.Put,Strike);
  if(inputData[8] == "C"){
      System.out.println("TypeCall"); // Check to see whether if stmt is ever true.
      payoff=new PlainVanillaPayoff(Option.Type.Call,Strike);
  } else{}

The print statement called inside the if statement never prints.

Any suggestions?

Upvotes: 1

Views: 160

Answers (7)

Curd
Curd

Reputation: 12417

If the type of inputData is String[] then I guess your problem is that you are comparing references instead of using the .equals()-function.

Correct:

if(inputData[8].equals("C"))

Upvotes: 1

David K
David K

Reputation: 690

If inputData is an array of chars?

if(inputData[8] == 'C') should solve it.

Otherwise you could try just to see if it does in fact contain "c"

Payoff payoff=new PlainVanillaPayoff(Option.Type.Put,Strike);
  if(inputData[8] == "C"){
      System.out.println("TypeCall"); // Check to see whether if stmt is ever true.
      payoff=new PlainVanillaPayoff(Option.Type.Call,Strike);
  } else{ System.out.println("inputData[8] contains: ->" + inputData[8] + "<-");}

Upvotes: -1

Federico Giust
Federico Giust

Reputation: 1793

Is the array a string array or a char array?

In the if clause you need to use " when comparing with strings or ' when doing it with char.

if it's a string try something like this in your if clause

stringname.charAt(x) == 'C'

Upvotes: 0

Montolide
Montolide

Reputation: 792

If inputData is a String[], you should use inputdata[8].equals("C") instead. If its not a String[], this will never fullfill, since they are different types :)

Upvotes: 1

assylias
assylias

Reputation: 328568

if inputData[8] is a string you should use the equals method instead of ==:

if("C".equals(inputData[8]))

also, putting "C" first makes sure you won't get a null pointer exception if `inputData[8]1 is null.

Upvotes: 2

T.J. Crowder
T.J. Crowder

Reputation: 1073998

Assuming the code compiles, the problem is that you're comparing strings with ==; you should use equals (or sometimes you want equalsIgnoreCase):

if(inputData[8].equals("C")){

Strings in Java are objects, and the == operator compares object identity (do two variables contain the same object reference), not the contents of the objects.

Upvotes: 3

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

This is because you are comparing Strings using ==. You should use equals instead.

if(inputData[8].equals("C"))

Upvotes: 3

Related Questions