我有我的GPA程序的问题,我必须使用两个数组来存储一个等级,它是学分,并计算GPA。到目前为止,除了gpa不会正确计算,我不知道我错过了什么(可能很简单),所有其他东西似乎都在工作。GPA数组计算错误
我的代码到目前为止是:
千兆帕类:
import java.util.*;
public class Gpa{
int[] credits = new int[4];
String[] grades = new String[4];
private int numCourses;
private int maxCourses;
private int sumOfCourses;
private int sumCredits;
private int sumPoints;
int newCredits;
int totalSum = 0;
int total = 0;
public Gpa(int noCourses){
maxCourses = noCourses;
numCourses = 0;
}
public void addCourse(int _newCredits, String newGrade){
for (int i=0; i<maxCourses; i++){
newCredits = _newCredits;
credits[i] = newCredits;
}
for (int i=0; i<maxCourses; i++){
grades[i] = newGrade;
}
switch (newGrade) {
case "A":
case "a":
newGrade = "4";
break;
case "B":
case "b":
newGrade = "3";
break;
case "C":
case "c":
newGrade = "2";
break;
case "D":
case "d":
newGrade = "1";
break;
case "F":
case "f":
newGrade = "0";
break;
}
sumPoints = sumPoints + (newCredits * Integer.parseInt(newGrade));
numCourses++;
}
public double calcGPA(){
for (int i=0; i<maxCourses; i++){
sumCredits = sumCredits + newCredits;
}
double gpa = (double)sumPoints/sumCredits;
return gpa;
}
} // end class
测试仪类:
import java.util.Scanner;
public class GpaTestEx2
{
public static void main (String[] args)
{
//declarations
Scanner in = new Scanner(System.in); //input object
int numCourses; //number of courses - can be changed
int credits; //number of credits for a course
String grade; //grade for course
//read in number of courses
System.out.print("Enter number of courses: ");
numCourses = in.nextInt();
//create Gpa object to hold specified number of courses
Gpa myGPA = new Gpa(numCourses);
//read in all courses and add course information to Gpa object
for (int k=0; k<numCourses; k++)
{
System.out.print("Enter credits for course " + (k+1) + ": ");
credits = in.nextInt();
System.out.print("Enter grade for course " + (k+1) + ": ");
grade = in.next();
myGPA.addCourse(credits, grade);
}
//print results
System.out.println();
System.out.printf("GPA is %4.2f%n", myGPA.calcGPA());
} //end main
}
当我进入课程学分和档次不正确地计算GPA 。例如,如果用户输入说有2门课程,其中一门课程有4学分,A分等级,另一门课程有3学分,等级为B,我应得3.57分时获得约4.17分的GPA。
任何帮助将是伟大的,我可能会或可能不会错过简单的东西。
为什么在'addCourse'中你将数组的每个元素都设置为新输入的等级?也许我在逻辑中错过了一些东西,但是好像你只想设置数组中的最新条目。并使用一个局部变量作为一个整数,而不是设置为一个字符串,然后解析该值。 – KevinO