Java GPA计算器循环

时间:2015-01-24 01:26:21

标签: java loops calculator

因此,此代码的整个目标是确定一个学期的GPA。它要求用户提供学期名称(即2014年秋季),课程名称,学分和成绩。它使用计算GPA将这些信息列入文本文件。

当你说" y"时,我似乎无法弄明白如何制作它。 (是)提示,"你想计算另一个学期(y / n)"它会创建另一个新的文本文件。

import java.util.Scanner;
import java.io.File;
import java.io.PrintStream;
import java.io.FileNotFoundException;

public class GpaCalcPeter {

public static void main(String[] args) throws Exception{
    processInput();
}

static void processInput() throws Exception {

    String yOrN;
    Scanner in = new Scanner(System.in);
    String className, semester, semesterFile;
    int credits, grade, totalCredits = 0, gradePoints = 0, n=0;
    double gpa;
    char choice = 'y';

    System.out.println ("Enter the semester: ");
    semester = in.nextLine();
    semester = semester.toLowerCase();
    semester = semester.replaceAll(" ", "");

    semesterFile = semester + ".txt";       
    PrintStream writer = new PrintStream(new File(semesterFile));

    while (choice != 'n') {

        System.out.println("Enter the course title: ");
        className = in.nextLine();

        System.out.println("Enter the number of credits: ");
        credits = in.nextInt();

        System.out.println("Enter the grade (A=4, B=3 etc.)");
        grade = in.nextInt();

        writer.printf("%s - %d" +" credits. Grade: %d", 
            className, credits, grade);
        writer.println("");

        gradePoints = gradePoints + grade * credits;
        totalCredits = totalCredits +credits;
        n = n + 1;

        in.nextLine();
        System.out.println("Would you like to enter another course? (y/n)");
        yOrN = in.nextLine();
        choice = yOrN.charAt(0);

        if (choice != 'y') {
            gpa = gradePoints / (float) totalCredits;
            System.out.printf("Overall GPA: %.2f", gpa);
            System.out.println("");

            System.out.println("Would you like to calculate for another semester (y/n)");
            yOrN = in.nextLine();
            choice = yOrN.charAt(0);

        }


    }

    gpa = gradePoints / (float) totalCredits;
    writer.printf("GPA: %.2f", gpa);
    writer.close();
}

}

1 个答案:

答案 0 :(得分:1)

首选使用in.next();代替in.nextLine(); 否则,您的代码在我的环境中正常工作。