尝试从文件

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

  

创建将读取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],Boolean.parseBoolean(obj[3]));
                blue.add(a);
                bcount++;
                if(obj[3] == "true") {
                    bCap = obj[0] + obj[1];
                }
            }
            else {
                Student a = new Student(obj[0],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,false
Lionel,Hailey,false
Genevive,Mckell,true
Esteban,Slaubaugh,false
Elden,Harte,false
Tasia,Rodrigue,false
Nathanial,Dentler,false
Valda,Nicoletti,false
Kary,Wilkerson,false
Coletta,Akey,false
Wilmer,Jack,false
Loreta,Agnew,true
Suzy,Cleveland,false
Pasty,Laprade,false
Candie,Mehaffey,false
Glady,Landman,true
Tierra,Mckeown,false

问题:我收到此异常消息

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 1

我不知道这是绑定到ArrayList还是String数组“ obj”,我也不知道如何解决它。

yk7732637 回答:尝试从文件

要对文件使用Scanner,必须通过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;
    }
}

希望有帮助。

,

我已经制作了一个与此类似的程序,其中我正在读取不同格式的文件(例如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();   


    }
}

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

本文链接:https://www.f2er.com/3043439.html

大家都在问