gpt4 book ai didi

Java FileInputStream 使用 if

转载 作者:行者123 更新时间:2023-12-02 07:25:25 26 4
gpt4 key购买 nike

我正在做的程序要求我使用 FileInputStream 来计算类(class)的成绩点。

我创建的类 Course 有一个方法:

public double getGradePoint ()
{
if (letterGrade == "A+" || letterGrade == "A")
gradePoint = 4.0;
if (letterGrade == "A-")
gradePoint = 3.7;
if (letterGrade == "B+")
gradePoint = 3.3;
if (letterGrade == "B")
gradePoint = 3.0;
if (letterGrade == "B-")
gradePoint = 2.7;
if (letterGrade == "C+")
gradePoint = 2.3;
if (letterGrade == "C")
gradePoint = 2.0;
if (letterGrade == "C-")
gradePoint = 1.7;
if (letterGrade == "D+")
gradePoint = 1.5;
if (letterGrade == "D")
gradePoint = 1.0;
if (letterGrade == "F")
gradePoint = 0.0;

return gradePoint;
}

在测试客户端中我有:

String subject;
String number;
String letGrade;

Course course1 = new Course ("ENGL", "1111", "D+");
FileInputStream file1 = new FileInputStream ("test transcript 1.txt");
Scanner readFile = new Scanner (file1);

while (readFile.hasNext ())
{
course1.setSubject (readFile.next ());
subject = course1.getSubject ();
course1.setNumber (readFile.next ());
number = course1.getNumber ();
course1.setLetterGrade (readFile.next ());
letGrade = course1.getLetterGrade ();
course1.getGradePoint ();
System.out.println (course1.toString ());
}

测试成绩单1.txt包含:

COMP 1631   A-
ENGL 1101 B
MATH 1200 C+

但由于某种原因,当我使用 course1.getGradePoint () 时,它总是返回 0.0

运行程序后:

COMP 1631   A-  (worth = 0.0)
ENGL 1101 B (worth = 0.0)
MATH 1200 C+ (worth = 0.0)

我尝试在 while 命令上方使用 course1.getGradePoint (),如下所示:

String subject;
String number;
String letGrade;

Course course1 = new Course ("ENGL", "1111", "D+");
course1.getGradePoint ();

FileInputStream file1 = new FileInputStream ("test transcript 1.txt");
Scanner readFile = new Scanner (file1);

while (readFile.hasNext ())
{
course1.setSubject (readFile.next ());
subject = course1.getSubject ();
course1.setNumber (readFile.next ());
number = course1.getNumber ();
course1.setLetterGrade (readFile.next ());
letGrade = course1.getLetterGrade ();
course1.getGradePoint ();
System.out.println (course1.toString ());
}

返回为:

COMP 1631   A-  (worth = 1.5)
ENGL 1101 B (worth = 1.5)
MATH 1200 C+ (worth = 1.5)

出于某种原因,它无法与 readFile.next () 一起使用。如果有人能帮助我,我将不胜感激。

最佳答案

- Java 中的 对象 使用 equals()String 进行比较> 在 Java 中是一个 Object,因此它遵循相同的规则。

- == 将用于比较 原始或检查是否两个或多个 对象引用变量是否指向堆上的同一个对象。

- 因此,您应该使用 equals()equalsIgnoreCase() (如果大小写不重要)来比较 字符串对象。

例如:

if (str1.equals(str2)){}

关于Java FileInputStream 使用 if,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13639405/

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