Thursday, July 21, 2022

[FIXED] How to create an Array with 2 Arrays inside of different types Java

Issue

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


Solution

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 };


Answered By - Jeroen Steenbeeke
Answer Checked By - Senaida (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.