0

I have 2 Arrays, one of String type and one of Int type. Is it possible to put both of these into another array?

Example for claification:

String[] grades = { A, B, C, D, E, F };
int[] marks = { 90, 80, 70, 60, 50 };

int[][] combined { grades, marks };

I need to be able to address each of them individually through the use of the combined array by typing combined[0][4] (to receive 'E') etc.

If this is possible, what would I use for my class return type? It is currently set to return int[][] but this doesn't work because a string can't be converted into an int.

My current theory is to have it return a string array and convert my integers to strings but this is inefficient and loses a lot of functionality, if anyone knows any smarter ways to do it I would love any advice.

Thank you for your time

0

2 Answers 2

2

Approach 1 : You could use a 2D object array.

int max = Math.max(grades.length,marks.length);

example :

Object[][] objArr = new Object[max][2];
objArr[0][0] = marks[0];
objArr[0][1] = grades[0];

The Array looks like {90,A}

to return a string you can get the grades and cast it to String

 return (String) obj[0][1];   // returns "A"

Approach 2 : You could use the ascii value for the grades and you can have them in 2D Integer array itself.

Integer[][] marksAndGrades = new Integer[max][2];
marksAndGrades[0][0] = marks[0];
marksAndGrades[0][1] = (int)grades[0].charAt(0);

Here the array looks like {90,65}

To return the grade based on the marks

return String.valueOf((char)(int)marksAndGrades[0][1]);   // returns "A"
Sign up to request clarification or add additional context in comments.

2 Comments

2D arrays in Java are not matrices, the contained arrays do not need to be equal in length
@JeroenSteenbeeke : Didn't notice that the given two arrays are uneven in length.Corrected the post now.
1

You could achieve this by first changing your array of numbers from int[] to Integer[], and then changing the combined array to Object[][]:

String[] grades = { "A", "B", "C", "D", "E", "F" };
Integer[] marks = { 90, 80, 70, 60, 50 };

Object[][] combined = { grades, marks };

Comments

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.