首页 > 解决方案 > 如何在java中将字符串插入字符串数组?

问题描述

我有以下获取用户输入的代码:

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 数组。我该怎么做才能避免这种情况?

谢谢你!!

标签: javaarraysexceptionjava.util.scanner

解决方案


再次查看代码

grade = Float.parseFloat(str);和 vars 声明
float grad; float[] grades = new float[100] 看不到任何grade

这不能确定编译!


推荐阅读