我想将studentGrade数组发送到“计算”方法来计算平均成绩,但如果文本文件的第一行是参数,我不能。当“if”方法运行时,即使两个字符串相等,它也会返回到 while 循环。
我尝试更改 .txt 的第一行,以防出现问题。但结果是一样的。它永远不会比较通缉犯是否在第一线。
static int studentNumber = 0;
static String[] studentGrade;
static String studentName = "";
static void makeList(String name) {
try(Scanner sc = new Scanner(new BufferedReader(new FileReader("C:\\Users\\User\\Desktop\\new_1.txt")))) {
boolean flag = true;
while (sc.hasNextLine()) {
flag = true;
String studentLine = sc.nextLine();
studentGrade = studentLine.split(",");
studentName = studentGrade[0];
if (studentName.equalsIgnoreCase(name)){
calculate(studentGrade);
flag = false;
break;
}
}
if (flag)
System.out.println("Couldn't found!");
}
catch (FileNotFoundException e) {
System.out.println("An error occured when the file was tried to opened.");
}
}
static void calculate(String[] a) {
int note1 = Integer.parseInt(a[1]);
int note2 = Integer.parseInt(a[2]);
int note3 = Integer.parseInt(a[3]);
double avg = Math.ceil((double)(note1 + note2 + note3) / 3);
System.out.println(a[0] + "'s average is: " + (int)avg);
}
我预计 if 情况为 true 并将数组发送到“计算”方法。它完成其工作,但学生位于 .txt 文件的第一行。例如,如果用户输入是 Michael,则会显示“找不到!”但如果输入是 John,它会给出平均值。
//First lines of .txt file
Michael,70,90,20
John,90,80,60
Molly,60,30,50
最佳答案
我使用您提供的值创建了一个文件:
Michael,70,90,20
John,90,80,60
Molly,60,30,50
当我尝试你的代码时,它似乎工作正常:
makeList("Michael");
makeList("John");
makeList("Molly");
返回
60
77
47
我怀疑你的文件开头有某种看不见的字符,这就是你的平等失败的原因。我在解析 XML 时多次遇到此类问题,解析器会提示我的文件不是以 XML 标记开头。
你能尝试用这三行创建一个全新的文件,并在这个新文件上再次尝试你的程序吗?
关于java - 无法将 .txt 文件的第一行与字符串进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54536163/