我是java的新手,并且正在接收此异常:java.lang.ArrayIndexOutOfBoundsException idk为什么会这样

问题描述 投票:0回答:1

所以基本上我收到了一个问题:

创建将读取members.txt文件内容的程序。成员必须分为3组,每组一个。处理完所有成员后,将有关每个团队有多少个成员以及什么是队长的信息输出到终端。文件值用以下模式用逗号分隔:

first_name, last_name, team_name, is_captain

这是我想出的代码(idk关于效率,因为我还很新):

package ssst.edu.ba;

import java.util.ArrayList;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scan = new Scanner("members.txt");
        int rcount = 0, bcount = 0, gcount = 0;
        ArrayList<Student> red = new ArrayList<Student>(5);
        ArrayList<Student> blue = new ArrayList<Student>(5);
        ArrayList<Student> green = new ArrayList<Student>(5);
        String line;
        String rCap = "";
        String bCap = "";
        String gCap = "";

        while ((line = scan.nextLine()) != null) {
            String[] obj = line.split(", ");
            if(obj[2] == "Red") {
                Student a = new Student(obj[0],obj[1],obj[2],Boolean.parseBoolean(obj[3]));
                red.add(a);
                rcount++;
                if(obj[3] == "true") {
                    rCap = obj[0] + obj[1];
                }
            }
            else if (obj[2] == "Blue") {
                Student a = new Student(obj[0],obj[1],obj[2],Boolean.parseBoolean(obj[3]));
                blue.add(a);
                bcount++;
                if(obj[3] == "true") {
                    bCap = obj[0] + obj[1];
                }
            }
            else {
                Student a = new Student(obj[0],obj[1],obj[2],Boolean.parseBoolean(obj[3]));
                green.add(a);
                gcount++;
                if(obj[3] == "true") {
                    gCap = obj[0] + obj[1];
                }
            }
        }
        System.out.println("There are " + rcount + " people on the red team.");
        System.out.println("There are " + bcount + " people on the blue team.");
        System.out.println("There are " + gcount + " people on the green team.");
        System.out.println("The captain for the red team is: " + rCap);
        System.out.println("The captain for the blue team is: " + bCap);
        System.out.println("The captain for the green team is: " + gCap);
    }
}

“ Student”类很简单,它具有3个私有String属性和一个私有bool值,它还具有一个带有4个参数的构造函数,用于将值设置为文本文档“ members.txt”中给出的值]

文本文档如下所示:

Ginny, Gullatt, Blue, false
Tiara, Curd, Red, false
Camie, Poorman, Green, false
Jammie, Hasson, Green, false
Lionel, Hailey, Blue, false
Genevive, Mckell, Red, true
Esteban, Slaubaugh, Blue, false
Elden, Harte, Red, false
Tasia, Rodrigue, Green, false
Nathanial, Dentler, Red, false
Valda, Nicoletti, Blue, false
Kary, Wilkerson, Green, false
Coletta, Akey, Blue, false
Wilmer, Jack, Red, false
Loreta, Agnew, Green, true
Suzy, Cleveland, Red, false
Pasty, Laprade, Blue, false
Candie, Mehaffey, Green, false
Glady, Landman, Blue, true
Tierra, Mckeown, Red, false
Glady, Laprade, Green, false

问题:我收到此错误消息线程“主”中的异常java.lang.ArrayIndexOutOfBoundsException:索引2超出长度1的范围我不知道这是绑定到ArrayList还是String数组“ obj”,而且我也不知道如何解决它。我不知道这是否与任何东西有关,但是我正在使用Intellij IDEA Ultimate。预先谢谢你:D !!

java arrays sorting arraylist split
1个回答
1
投票

我已经制作了一个与此类似的程序,其中我正在读取CSV EXCEL等不同格式的文件,并对它执行操作,因此您去检查一下该代码是否是行业级别的代码,将会带来更多的曝光度,而不仅仅是解决方案。

https://github.com/NahidAkhter/feeCalculator.git

总之,我可以在下面提供一个摘要1)TextTransctionReader.java

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import com.feecalculator.Constant.FILETYPE;
import com.feecalculator.Transaction;


public class TextTransctionReader extends AbstractTransactionReader implements ITransactionManager {


    @Override
    public void readTransaction(File transactionFile) {


        BufferedReader br = null;
        String line = "";
        String cvsSplitBy = ",";

        try {

            br = new BufferedReader(new FileReader(transactionFile));
            while ((line = br.readLine()) != null) {
                String[] transactionAttributes = line.split(cvsSplitBy);
                Transaction transaction = getTransaction(transactionAttributes); 
                saveTransaction(transaction);

            }        
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    @Override
    public ITransactionManager readFile(FILETYPE fileType) {
        if(fileType == FILETYPE.TEXT){
            return TrasactionReader.getTrasactionReaderInstance().readTextFile();
        }
        return null;
    }


}

下面是主类:

import java.io.File;

import com.feecalculator.Constant.FILETYPE;
import com.feecalculator.reader.ITransactionManager;
import com.feecalculator.reader.TrasactionReader;


public class MainFeeCalculator {
    public static void main(String[] args) {

        File transactionfile = new File(new File("").getAbsolutePath(),"resource/Input_java.xlsx");
        ITransactionManager tranction= TrasactionReader.getTrasactionReaderInstance().readFile(FILETYPE.EXCEL,transactionfile);     
        tranction.displayTransactionReport();   


    }
}

我希望这能解决您的问题。


1
投票

要对文件使用扫描仪,必须通过File类提供文件,如下所示:

import java.io.File;
import java.io.FileNotFoundException;

public static void main(String[] args) throws FileNotFoundException {
    Scanner scan = new Scanner(new File("./members.txt"));

    /* ...Some code */
}

实际上您是从仅包含文本“ members.txt”的流中读取的

扫描仪(字符串源)

构造一个新的扫描仪,该扫描仪生成从指定的字符串扫描的值。

所以您正在使用构造函数htat接收字符串作为参数,而不是使用文件的字符串。看https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#Scanner(java.lang.String)

此外,您还必须使用hasNextLine函数,例如:

while (scan.hasNextLine()) {
    line = scan.nextLine();

/* some code */

}

否则,您将获得例外java.util.NoSuchElementException

这里是程序的有效版本:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;

public class Main {

    public static void main(String[] args) throws FileNotFoundException {
        Scanner scan = new Scanner(new File("./members.txt"));

        ArrayList<Student> red = new ArrayList<Student> (5);
        ArrayList<Student> blue = new ArrayList<Student> (5);
        ArrayList<Student> green = new ArrayList<Student> (5);

        // we use a map to save the index where is the captain in the array list
        HashMap<String,Integer> captains = new HashMap <String, Integer> ();

        while (scan.hasNextLine()) {
            String[] rawStudent = scan.nextLine().split(", ");
            Student student = new Student(rawStudent);

            ArrayList selectedTeam = red;

            // we select dynamically the list where the student will be added
            switch (student.getTeam()) {
                case "Red": selectedTeam = red; break;
                case "Blue": selectedTeam = blue; break;
                case "Green": selectedTeam = green; break;
            }

            selectedTeam.add(student);

            if (student.isCaptain()) {
                int lastAddedIndex = selectedTeam.size() - 1;

                captains.put(student.getTeam(), lastAddedIndex);
            }
        }

        System.out.println("There are " + red.size() + " people on the red team.");
        System.out.println("There are " + blue.size() + " people on the blue team.");
        System.out.println("There are " + green.size() + " people on the green team.");

        System.out.println("The captain for the red team is: " + red.get(captains.get("Red")).getFullName());
        System.out.println("The captain for the blue team is: " + blue.get(captains.get("Blue")).getFullName());
        System.out.println("The captain for the green team is: " + green.get(captains.get("Green")).getFullName());
    }
}

class Student {
    private String name;
    private String lastName;
    private String team;
    private boolean isCaptain;

    public Student(String p1, String p2, String p3, boolean p4) {
        this.name = p1;
        this.lastName = p2;
        this.team = p3;
        this.isCaptain = p4;
    }

    public Student(String[] list) {
        this(list[0], list[1], list[2], Boolean.parseBoolean(list[3]));
    }

    public String getFullName() {
        return this.name + " " + this.lastName;
    }

    public boolean isCaptain() {
        return this.isCaptain;
    }

    public String getTeam() {
        return this.team;
    }
}

希望有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.