I am currently studying for my final Java exam at university and I'm doing the past papers to prepare. I'm stuck with the following problem, I need to create a method that receives a string array of Grades and calculates the total, converting the grades to UCAS tariff points (the question before), I created the following:
public class Test
{
public static void main(String[] args)
{
System.out.println(getUcasTariff("B"));
}
public static int getUcasTariff(String grade)
{ int points = 0;
if(grade.equals("A*"))
{
return points = 56;
}
else if(grade.equals("A"))
{
return points = 48;
}
else if(grade.equals("B"))
{
return points = 40;
}
else if(grade.equals("C"))
{
return points = 32;
}
else{
return points = 0;
}
}
public static int getTotalUcasTariff(String[] grades)
{ int[] totalPoints = new int[grades.length];
for(int i = 0; i < grades.length; i++) {
Here, I need to iterate through the grades array and call the method getUcasTariff
that changes the string to an int and stores it into the new array I created, totalPoints
. I can't make it work though.
}
int sum = 0;
for (int i : totalPoints) {
sum += i;
}
return sum;
}
}
It would be great if someone can point me into the right direction, or maybe point out a better way to do this.
Just iterate through the array, transform each grade individually and add the return values:
public class Test {
public static void main(String[] args) {
System.out.println(getTotalUcasTariff(args));
System.out.println(getTotalUcasTariff(new String[] {"B", "A*"}));
}
public static int getUcasTariff(String grade) {
int points = 0;
if (grade.equals("A*")) {
points = 56;
} else if (grade.equals("A")) {
points = 48;
} else if (grade.equals("B")) {
points = 40;
} else if (grade.equals("C")) {
points = 32;
} else {
points = 0;
}
return points;
}
public static int getTotalUcasTariff(String[] grades) {
int totalPoints = 0;
for (String grade : grades) {
totalPoints = totalPoints + getUcasTariff(grade);
}
return totalPoints;
}
}
Output with command line parameters and without
$ java Test.java "A*" "B"
96
96
$ java Test.java
0
96