Question

I have variables of type long: hour_6days, hour_7days, hour_8days and hour_13days.

I have a string array:

String[] jj = rule.split(del);

where jj[0] contains the one of the numbers 6 or 7 or8 or 13.

How to change the above long variables according to the value in jj[0] ?

For example, how can I write the below, such that right hand side of the assignment is equivalent to the left hand side variable like:

hour_6days = "hour_"+jj[0]+"6days"; //this is invalid as hour_6days is of long type.

To be more clear,

If jj[0] contains 6, then I will use long variable's hour_6days value. If jj[0] contains 7, then I will use the long variable's hour_7days value.

The values I am using to set certain TextView like:

TextView tt2 = (TextView) v.findViewById(R.id.th3);

tt2.setText(hour_7days);

UPDATE:

I want to reuse the code in order to avoid multiple conditions. As said, in some conditions I am using tt2.setText(hour_7days); and in some other conditions I am using tt2.setText(hour_6days); and so on. I want to avoid the conditions and just simple use tt2.setText(hour_6_or_7_or_8days).

Was it helpful?

Solution

Try using a Map, HashMap is a possible choice.

HashMap<Integer, Long> dayValues = new HashMap<Integer, Long>();

dayValues.put(6,  <put long value for 6 days here>);
dayValues.put(7,  <put long value for 7 days here>);
dayValues.put(8,  <put long value for 8 days here>);
dayValues.put(13, <put long value for 13 days here>);

...

tt2.setText(dayValues.get(jj[0]).toString());

This will use the integer value in jj[0] to get the corresponding string value from the map and set it into tt2.

OTHER TIPS

If I understand you right you would use enum, like:

public enum EHourDay{

    hour_6days(6),  // actually I would use Upper case
    hour_7days(7),
    hour_8days(8),
    hour_13days(13);

    public static EHourDay
    FromIntToEnum(
            int value ) throws Exception
            {
        for ( EHourDay c : EHourDay.values() ) {
            if ( c.mId == value ) {
                return c;
            }
        }

        throw new Exception( new StringBuilder("Illegal EHourDay: ").append(value).toString() );
            }

    public int
    FromEnumToInt() {
        return mId;
    }

    private EHourDay( int id )
    {
        mId = id;
    }

    private int mId;
}

Main

public static void main(String[] args) throws NumberFormatException, Exception {

        String rule = "6 7 8 13";

        String[] jj = rule.split(" ");

        for(String str : jj){
            EHourDay hourDay = EHourDay.FromIntToEnum(Integer.parseInt(str));

            System.out.println(hourDay);
        }

    } 

After you can type something like:

tt2.setText(EHourDay.FromIntToEnum(Integer.parseInt(str)));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top