I have to create an array of grades and perform operations. Now I have to use generics to do so and I pass the array to the generic function and try it using a conditional if else statement but the if else isn't even considered, the for loop works though.
Here is my code for the question.
import java.util.*;
class Calculation
{
public static <T> void gpa(T[] elements)
{
for(T element:elements)
{
System.out.println(element);
}
int elem[]=new int[5];
int i=0;
int sum=0;
for(T element:elements)
{
if(element=="A")
{
elem[i]=9;
}
if(element=="B")
{
elem[i]=8;
}
if(element=="C")
{
elem[i]=7;
}
if(element=="D")
{
elem[i]=6;
}
if(element=="E")
{
elem[i]=5;
}
if(element=="F")
{
elem[i]=2;
}
if(element=="2")
{
System.out.println("The grade is F.");
}
if(element=="5")
{
System.out.println("The grade is E.");
}
if(element=="6")
{
System.out.println("The grade is D.");
}
if(element=="7")
{
System.out.println("The grade is C.");
}
if(element=="8")
{
System.out.println("The grade is B.");
}
if(element=="9")
{
System.out.println("The grade is A.");
}
i++;
}
for(int j=0;j<5;j++)
{
sum+=elem[j]+sum;
}
int avg=sum/5;
System.out.println("The average is " + avg);
}
}
public class Calc
{
public static void main(String args[])
{
Calculation obj=new Calculation();
Character arr1[]={'A','B','C','A','A'};
Integer arr2[]={9,9,5,2,8};
System.out.println("The CGPA will be");
obj.gpa(arr1);
System.out.println("The grade will be");
obj.gpa(arr2);
}
}
I expected the code to run considering the if else but that isn't working. I tried using a switch statement and that failed. The output with the code attached doesn't raise any errors but doesn't perform any comparisons with the conditional statements. Taking the values in conditional statements as characters/integers also gives an error.