【问题标题】:Method with one parameter whose data type is ArrayList of Passenger一个参数的方法,其数据类型为Passenger的ArrayList
【发布时间】:2020-04-13 15:06:20
【问题描述】:

所以,我有了printStats这个方法,它的参数pList的数据类型是Passenger的ArrayList:

public static void printStats(ArrayList<Passenger> pList) {
            Scanner file = new Scanner( new File( "titanic.csv" ) );
            DecimalFormat percent = new DecimalFormat("#.0%");
            String header = file.nextLine();
        while (file.hasNextLine()){
            String gender;
            String survived;
            int count = 0;
            int males = 0;
            int females = 0;
            int survivedMales = 0;
            int survivedFemales = 0;
            for(int i=0; i<pList.length;i++) {
                if (gender.equals ("M"))
                { males++;
                    if (survived.equals("yes"))
                        survivedMales ++;}
                        else
                        {
                            females++;
                        }
                            if (survived.equals("yes"))
                                survivedFemales ++;}
                        count++
            System.out.println("Total number of passengers: " + count);
            System.out.println("Total number of male passengers: " + males);
            System.out.println("Total number of female passengers: " + females);
            System.out.println("Total number of male passengers survived: " + survivedMales);
            System.out.println("Total number of female passengers survived: " + survivedFemales);
            System.out.println("Survival rate of male passengers: " + percent.format(survivedMales/males));
            System.out.println("Survival rate of female passengers: " + percent.format(survivedFemales/females));
            }

我一直在 for 循环中出现语法错误,特别是在“i

for(int i=0; i<pList.length;i++)

任何帮助将不胜感激。

【问题讨论】:

  • 你用什么样的编辑器来写Java?大多数编辑器都有一个快捷方式来为您对齐代码,以便更轻松地查看您在哪里犯了错误。
  • 我在 Eclipse 中,它突出显示了 pList.length 中的“长度”,但我仍然不确定如何修复它
  • Eclipse 中的自动格式化: CTRL + SHIFT + F 这将使您下次更容易看到错误。我在下面支持 Code-Apprentice 的答案,因为他回答了您的实际问题。

标签: java arrays list loops for-loop


【解决方案1】:

我建议你看看the documentation for ArrayList。向下滚动时,您将看到没有名为 length 的公共字段,因此 pList.length 无效。这就是 Eclipse 所抱怨的。相反,您会发现有一个名为size() 的方法。所以你需要用pList.size()替换pList.length

【讨论】:

    猜你喜欢
    • 2011-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-11
    • 2013-04-01
    • 2012-05-28
    相关资源
    最近更新 更多