Home > front end >  Can't I print an array list using the value of a char(converted int to strings)?
Can't I print an array list using the value of a char(converted int to strings)?

Time:09-22

I tried to print the array using the value of a char but it didn't work.. somehow my brain thought it would.. I'm trying to convert numbers to its roman value btw this is just a test.. can anyone teach me how it would work? thanks!!

public class test {

public static void main(String[] args) {

String[] ones = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX" };

    int num = (123);

    String s = Integer.toString(num);
    
    char result = s.charAt(0);
    System.out.println(ones[result]);
}

}

CodePudding user response:

char result = s.charAt(0);
System.out.println(ones[result]); //which asking index 49th element that is not possible for you case due array size

Arrays have index that start from 0 to onward and index number should be integer, but you are giving char as index which compiler doing auto-boxing and return its ascii value for char 1 which is 49. See below, it will gives desired result

System.out.println(ones[Integer.parseInt(String.valueOf(result))]);
  • Related