tags:

views:

78

answers:

4

I want to write a conditional statement, depending on whether a variable is an int or double, i.e

if (x is a double)
  do stuff
else if(x is an int)
  do stuff
else
  do stuff

I know this might not be a good idea, but its my only choice for now. Is this possible?

+4  A: 

I have no idea how x could be an int or a double without you knowing at compile time, but

void dostuff(int x) {
    do stuff...
}

void dostuff(double x) {
    do stuff...
}

then

dostuff(x)

will call the appropriate method.

Skip Head
+1  A: 

Edited to add:I don't think this question is really what you want, based on your comment to the original question. I'll post a comment on the other question to try and offer some assistance to yoru real issue.

As Bill the Lizard says, you'll know at compile time what type a primitive is:

public void foo(int x, double y){...}

On the other hand, if you're putting your types inside another object, like

Vector v = new Vector();
v.add((int)1);
v.add((double)1.0));

then you're really dealing with objects not primitives. Each primitive has a corresponding class:

  • int has Integer
  • double has Double
  • float has Float
  • boolean has Boolean
  • etc.

You can use the instanceof keyword to determine what type you're dealing with (you can do this with any class):

if( x instanceof Double ) {
  doDoubleThing();
} else if( x instanceof Integer ) {
  doIntegerThing();
} // and so on
atk
A: 

What atk wrote is valid if you have the ability to use two methods. If this isn't an option or you don't want to do this (personally think it might be more readable and less repetitious to have one method and just do an if-else branch, depends on your code), you can use reflection:

Class intClass = Integer.class;
Class doubleClass = Double.class;
if intClass.isInstance(foo)
    bar();
else if doubleClass.isInstance(foo)
    spam();
else
    eggs();

This might not necessarily be the best solution. Just thought you should know about it.

Rafe Kettler
+1  A: 

I'm guessing you're trying to check if a number has a decimal part or not.

double n;
if(n-floor(n)>0)
    it has a decimal part
else
    it's an integer
Utkarsh Sinha