HizarSajjad
HizarSajjad

Reputation: 13

how to access specific element of one element in three arrays

String Title[] = {"ICT", "ENG", "MATH", "PHY", "CS", "PKS"};

String C_Code[] = {"CS-164", "ENG-101", "MATH-107", "PHY-117", "CS-102", "PKS-101"};

int Credit_H[]= {4, 3, 3, 3, 4, 2};

I Have these three arrays. in this problem if I give a course title, for example, I give "MATH" then in the second array program will show me Math's Course code and after that in the third array Credit hour, math's credit hour will display me. in other words, if I enter any Course title then its Course Code and Credit hour will show me on the screen

Upvotes: 1

Views: 53

Answers (3)

Huy Nguyen
Huy Nguyen

Reputation: 2061

I assumed all arrays have the same length with same index.

So you can find the index of first array.

 index = 2 with MATH.

That mean you have to traverse first array to find the index.

Then you can use above index to access C_Code and Credit_H.

String code = C_Code[index];

int credit = Credit_H[index];

PS: be aware about item not found, you should return index=-1, then you need to check index > -1, then you can access code/credit... otherwise show warning or throw exceptions...

Upvotes: 0

Jake
Jake

Reputation: 13

Just allow user to make a selection.

int ch = scan.nextInt();
System.out.println("Title: " + Title[ch] + "; C_Code: " + C_Code[ch] + "; Credit_H: " + Credit_H[ch]);

Note: the value of ch must be between 0 and the length of the arrays. If you want to start 1 You need to add 1 to ch ex. C_Code[ch + 1]

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521053

I think you actually want two hashmaps here:

Map<String, String> codes  = new HashMap<>() {{
    put("ICT",  "CS-164");
    put("ENG",  "ENG-10");
    put("MATH", "MATH-107");
    put("PHY",  "PHY-117");
    put("CS",   "CS-102");
    put("PKS",  "PKS-101");
}};

Map<String, Integer> credits  = new HashMap<>() {{
    put("ICT",  4);
    put("ENG",  3);
    put("MATH", 3);
    put("PHY",  3);
    put("CS",   4);
    put("PKS",  2);
}};

Upvotes: 0

Related Questions