gpt4 book ai didi

Java GPA 计算器循环

转载 作者:行者123 更新时间:2023-12-01 11:59:06 26 4
gpt4 key购买 nike

所以这段代码的整个目标是计算一个学期的 GPA。它要求用户提供学期名称(即 2014 年秋季)、类(class)名称、学分和成绩。它将这些信息列出到一个文本文件中,并计算 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();
}

}

最佳答案

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

关于Java GPA 计算器循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28121315/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com