1

I am getting a bunch of strings and I would like to check each of them if they match to a specified type.

I could do it like this:

String[] strings = ...;
for(int i = 0; i < strings.length; i++) {
    switch(i) {
    case 0:
        try {
            Integer.parseInt(strings[i]);
        } catch(Exception e) {
            valid = false;
        }
        break;
    case 1:
        break;
    ...
    }
}

But since it should be easy to add new conditions I want to create something like this

Type[] conditions = new Type[2];
conditions[0] = int;
conditions[1] = long;

and then check the whole stringarray.

Thanks in advance!

8
  • 1
    What do you mean by "check each of them if they match to a specified type"? Commented Feb 29, 2012 at 10:17
  • 1
    You probably shouldn't be using a switch in the way you are. Commented Feb 29, 2012 at 10:19
  • 1
    IMHO, if you add a case label for each value of i, you don't need the loop. Putting that aside, what's your problem? Anyway, I'd suggest using regex for checking the string values since in this case using exceptions seems a bit out of place. Commented Feb 29, 2012 at 10:21
  • 1
    You are using switch statement in a wrong way. For example your attempt to case to Integer in the first case is in case implementation, which should be in condition part, obviously. Commented Feb 29, 2012 at 10:23
  • 1
    You could use wrapper classes, and add all of considered types to conditions. You have docs.oracle.com/javase/1.5.0/docs/api/java/lang/… docs to classes like Integer, Double, etc. Commented Feb 29, 2012 at 10:25

2 Answers 2

2

I think perhaps this is what you're after? The main code loops through all Strings, and then runs each possible "check" on that String in turn. The "check" code itself is stored in an array, which contains objects with a single check(String) method, which is overridden inline. You can make a check() method do anything you need, as long as it works from the standard signature, so if you need regular expression checks or something more complex then that would also work fine.

public class TestTypes
{
    public static void main(String[] args)
    {
        String[] strings = new String[] {"123", "9999999999999", "50.4", "not a number"};

        for(String str : strings)
        {
        System.out.print("'" + str + "': ");
            for( TypeChecker checker : typesToCheck)
            {
                if(checker.check(str))
                {
                    System.out.print(checker.type.getSimpleName() + " ");
                }
            }
            System.out.println();
        }
    }


    static abstract class TypeChecker
    {
        public final Class type;
        public abstract boolean check(String s);

        TypeChecker(Class type)
        {
            this.type = type;
        }
    }

    // A list of the code for all the checks
    static TypeChecker[] typesToCheck = 
    {
            new TypeChecker(Integer.TYPE) // is Integer
            {
                public boolean check(String s)
                {
                    try{Integer.parseInt(s);}
                    catch(Exception e)
                    {return false;}
                    return true;
                }
            },

            new TypeChecker(Long.TYPE) // is Long
            {
                public boolean check(String s)
                {
                    try{Long.parseLong(s);}
                    catch(Exception e)
                    {return false;}
                    return true;
                }
            }, 

            new TypeChecker(Double.TYPE) // is Double
            {
                public boolean check(String s)
                {
                    try{Double.parseDouble(s);}
                    catch(Exception e)
                    {return false;}
                    return true;
                }
            }, 
    };
}

This produces the output:

'123': int long double 
'9999999999999': long double 
'50.4': double 
'not a number': 

This solution is a lot more verbose, and has a level of indirection which has the potential to make it confusing, so if you've only got a small number of possible types, I'd just inline the lot of them and save everyone the trouble!

This sort of approach is only really a good approach if you have complicated algorithms which need to be run in the tests, or if you need to be able to customize which tests are being executed dynamically at runtime.

Sign up to request clarification or add additional context in comments.

Comments

1

Assuming your code checks for 3 datatypes only..Your code could be something like this:

OUTER:  for(int i = 0; i < strings.length; i++)
    {

    if(strings[i].contains("."))
    {
    //float ..since a '.' is present

    continue OUTER;
    }

    else 
    {
    for(int j=0;j<strings[i].length;j++)
    {

    if(strings[i].charAt(j).isCharacter()) // string contains a character
    {
    //text ...since a character is present
    continue OUTER;

    }
    else
    {
    //int ..no character and no '.' hence an int

    }

    }
    }//end of inner for
    }//end of outer for

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.