我有我的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