如何在java中为GPA计算器划分变量

时间:2016-01-26 21:58:19

标签: java

我正在为一类我的GPA计算器工作。我一直收到一个错误,该错误与我正在尝试对GPA计算进行的划分有关,并且我对子字符串的语法以及如何正确使用它们有困难。下面是我到目前为止的代码。如果你看到任何我能解决的问题,那就不复杂了,我愿意接受所有的建议。

import java.util.Scanner;

public class GPA
{
    public static void main(String[] mydata)
    {
        Scanner sc = new Scanner(System.in);        
        String choice = "";
        String cnum;
        String grade;
        double points;
        double gpa = 0;
        int count = 0;
        String credit= "", totalCredit = "";

        while (!choice.equalsIgnoreCase("Q")) 
        {
            cnum = (mydata[0]);
            grade = (mydata[1]);

            if (grade.equalsIgnoreCase("A")) {points = 4.0;} 
            else if (grade.equalsIgnoreCase("B")) {points = 3.0;} 
            else if (grade.equalsIgnoreCase("C")) {points = 2.0;}         
            else if (grade.equalsIgnoreCase("D")) {points = 1.0;}
            else if (grade.equalsIgnoreCase("F")) {points = 0.0;}

            credit = cnum.substring(3,4);

            //System.out.println("credits = " + totalCredit);

            System.out.println("GPA = " points/Double.parseDouble(credit));
            System.out.print("Enter next course number and grade or ‘Q’ to quit: ");
            System.out.println();
            choice = sc.nextLine();
        }
        System.out.println("Bye!");
    }
}

3 个答案:

答案 0 :(得分:0)

确保包含+以将字符串连接在一起:)

System.out.println("GPA = " + (points/Double.parseDouble(credit)));

答案 1 :(得分:0)

我相信你想在这里连接。

System.out.println("GPA = " + (points/Double.parseDouble(credit)));

而不是

System.out.println("GPA = " (points/Double.parseDouble(credit)));

如果你想要

int theGpa = points/Double.parseDouble(credit));
System.out.println("GPA: " + theGpa);

答案 2 :(得分:0)

不错但你的代码有几个语法错误:

  1. println参数需要与+连接:

    System.out.println("GPA = " + points / Double.parseDouble(credit));
    
  2. 需要初始化局部变量points,因为if-else条件并非详尽无遗(即:grade的运行时范围为A,B,C, D或F但grade在技术上可以分配给mydata[1]中的任何内容。添加else条件或将初始值分配给points

    double points = 0.0;