0

I would like to create a 2D array but get the row and column value from an integer, example;

    Integer Col = 8;
    Integer Row = 200;

    String[][] list;

    list = new String [Row][Col];

Of course, this is not compling. Im getting a Type mismatch: cannot convert from int to String error but I am not trying to convert an int to a String, I just want the Integer value to set the array length.

2
  • 1
    This part works fine for me ! Share the whole code Commented Sep 28, 2013 at 20:00
  • public class Beta1 { public static void main(String[] args) { Integer Col = 8; Integer Row = 200; int i = 0; String[][] list; list = new String [Row][Col]; list[5][100] = 27; System.out.println(list[5][100]); } } Commented Sep 28, 2013 at 20:06

2 Answers 2

1

Are you sure your environment setup is correct? Because your code looks good, see here .

public class Main {

    public static void main( String args[] ) {
        Integer Col = 8;
        Integer Row = 200;

        String[][] list;

        list = new String[Row][Col];
        System.out.println( list.length );

    }
}

I just renamed the class and added a print statement to show something useful, nothing more :)

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

Comments

0

The reason why you are getting the "cannot convert from int to String error" is because you are storing an 27(integer) to list(which is a string datatype). list[5][100] = 27. For storing an integer into a string datatype, you have to explicitly convert the integer to string using String.valueOf() or Integer.toString --

public class Beta1 { 
  public static void main(String[] args) { 
    Integer Col = 200; 
    Integer Row = 8; 
    int i = 0; 
    String[][] list; 
    list = new String [Row][Col]; 
    list[5][100] = String.valueOf(27); 
    System.out.println(list[5][100]); 
  } 
}

2 Comments

This is giving me; Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 100 at Beta1.main(Beta1.java:16)
Ahh. this was because the number of columns was 8 and you are accessing the 100 position. Change the row and column values, I have edited the code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.