【发布时间】:2020-07-28 08:14:52
【问题描述】:
我有以下获取用户输入的代码:
456589 maths 7.8 english 8.6 end
654564 literature 7.5 physics 5.5 chemistry 9.5 end
并将句子开头的代码存储在名为 Grades 的数组中,并将代码存储在另一个名为 person 的数组中。我需要使用这两个数组以便稍后显示每个人在每节课中的平均成绩。
我的代码如下
import java.util.Scanner;
public class Student
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
String currentAnswer = "";
String userWords = "";
String am = "";
String subj = "";
float grad;
float[] grades = new float[100];
String[] person = new String[100];
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 += 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(" ");
for (String str : wordsplit)
{
try
{
grade = Float.parseFloat(str);
}
catch(NumberFormatException ex)
{
person = str;
}
}
}
System.out.println("Enter your a.m. as well as the subjects which you sat in finals");
}
}
错误消息涉及行
grades = Float.parseFloat(str);
person = str` --> `String cannot be converted to String[]`<br>
似乎禁止将 String 转换为 String 数组。我该怎么做才能避免这种情况?
谢谢!!
【问题讨论】:
-
您能否详细解释一下该错误
-
当然可以。每当我运行它时,我都没有在数组等级和人员中得到想要的结果。此外,当我尝试显示以下输出时 --> (456589 的平均结果为
)我也会收到一条错误消息 -
person是一个数组,str是一个字符串——完全不同的类型。您不能将一个分配给另一个。你应该研究一下如何设置数组的元素。
标签: java arrays exception java.util.scanner