【问题标题】:Java GPA Calculator LoopJava GPA 计算器循环
【发布时间】:2015-01-24 01:26:21
【问题描述】:

所以这段代码的全部目标是计算一个学期的 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();
}

}

【问题讨论】:

  • 那么我会在我已有的循环中添加一个while循环吗?
  • 抱歉,没看到内循环。 in.next 会是个不错的选择

标签: java loops calculator


【解决方案1】:

更喜欢使用in.next(); 而不是in.nextLine(); 否则,您的代码在我的环境中可以正常工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-19
    • 1970-01-01
    相关资源
    最近更新 更多