JAVA: Make a cast from String to Int within a try catch with variables with incremental names

0

As it says in the title I'm trying a way in which in a single loop can do with a try catch the casting of many variables at the same time taking advantage of these variables have incremental names type: s1, s2, s3, s4. .. concatenated to point to these variables. An example of code that I would like to do is this:

public class JavaStringToIntExample
{
 public static void main (String[] args)
 {
   // String s = "fred";  // use this if you want to test the exception below
   String s1 = "100";
   String s2 = "101";
   String s = "s";
   try
   {
     // the String to int conversion happens here
     for(int i=0;i<2;i++){
        int j = Integer.parseInt(s+"+"+i).trim();
        System.out.println(j);
}
     // print out the value after the conversion
   }
   catch (NumberFormatException nfe)
   {
     System.out.println("NumberFormatException: " + nfe.getMessage());
   }
 }
}
    
asked by I.G 12.05.2017 в 18:02
source

1 answer

0

If I understood where you want to go, I commented that you should modify the lines that are within the for cycle.

// the String to int conversion happens here
for(int i=0;i<2;i++){
    int j = Integer.parseInt(s+"+"+i).trim();
    System.out.println(j);
 }

For the following:

// the String to int conversion happens here
 for(int i=0;i<2;i++){
    System.out.println(s + i);
}

Since it is not necessary to make a parseInt since I is of integer type and it is impossible to cast a letter.

I hope it helps you. Greetings.

    
answered by 10.08.2018 в 15:38