为什么 Arraylist 不接受它自己的方法?



我有一个程序,我想在其中打印学校每个学生的科目平均值。

输入应该看起来像这个

000555 maths 88.7 physics 55.6 end 

"结束"是一个关键字,表示学生的输入数据已终止。只要有人键入stop,程序就会终止。

我将用户输入的所有等级存储在ArrayList中。然而,当我运行程序时,我会收到以下错误消息:

error: no suitable method found for add(String) (grades.add(str))
method Collection.add(Float) is not applicable
(argument mismatch; String cannot be converted to float)
error: no suitable method found for set(String) (grades.set(str))
etc...

我知道我不能直接将String转换为Float,但我尝试了所有方法,但仍然不起作用。为了让编译器接受这些方法,我应该做些什么?

我的代码如下:

import java.util.Scanner;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Student
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
String currentAnswer = "";
String userWords = "";
ArrayList<Float> grades = new ArrayList<Float>();
System.out.println("Enter your a.m. as well as the subjects which you sat in finals");
while(!currentAnswer.equals("end"))
{
currentAnswer = s.nextLine(); // reads the number or word
userWords += "n" + currentAnswer ;
if(currentAnswer.equals("000000"))
{
System.out.println("The sequence of numbers you entered is: "+userWords);
System.out.println("Exiting...");
System.exit(0);
}
String[] wordsplit = currentAnswer.split(" ");
String pattern = "^\d+$";
Pattern p = Pattern.compile("\d+");
stud.clear();
grades.clear();
for (String str : wordsplit)
{
Matcher m = p.matcher(str);
if(str.matches("^\d+$")){
String name = new String(str);
System.out.println("Code is: "+str);}
if(m.find()){
grades.add(str);
System.out.println("The numbers are: "+str);}   
}
grades.set(0,0);
float sum = 0;
for( float i : grades)
{
sum+= i;
}
float avg = sum / grades.size();
System.out.println("The average of student "+name+" is "+avg);
} //while
}//main
}//class

您正试图将String添加到Float类型的arrayList中

if(m.find()){
grades.add(str);    //str needs to be of float type

最新更新