Java,从文件中读取两种不同类型的变量,并在以后将它们用作对象

时间:2017-12-04 15:13:08

标签: java arraylist bufferedreader filereader

我正在开发一个项目,该项目基于从文件中读取文本并将其作为对象放入我的代码中。

我的文件包含以下内容: (忽略要点)

  • 4
  • 圣诞派对
  • 20
  • 情人节
  • 12
  • 复活节
  • 5
  • 万圣节
  • 8

第一行声明我的文本文件中有多少“派对”(4 btw) 每一方都有两行 - 第一行是名称,第二行是可用的地点数。

例如,圣诞派对有20个名额

这是我的代码,用于将文件中的信息保存为对象。

public class Parties
{
   static Scanner input = new Scanner(System.in);


  public static void main(String[] args) throws FileNotFoundException
  {

     Scanner inFile = new Scanner(new FileReader ("C:\\desktop\\file.txt")); 

     int first = inFile.nextInt();
     inFile.nextLine();


    for(int i=0; i < first ; i++)
    {
        String str = inFile.nextLine();
        String[] e = str.split("\\n");

        String name = e[0];
        int tickets= Integer.parseInt(e[1]); //this is where it throw an error ArrayIndexOutOfBoundsException, i read about it and I still don't understand

        Party newParty = new Party(name, tickets);
        System.out.println(name+ " " + tickets);
    }

这是我的SingleParty类:

public class SingleParty
{
    private String name;
    private int tickets;


    public Party(String newName, int newTickets)
    {
        newName = name;
        newTickets = tickets;

    } 

有人可以向我解释如何处理此错误?

谢谢

3 个答案:

答案 0 :(得分:1)

str只包含派对名称,并且分割它不会起作用,因为它不会有&#39; \ n&#39;那里。

在循环中应该是这样的:

String name = inFile.nextLine();
int tickets = inFile.nextInt();

Party party = new Party(name, tickets);

// Print it here.

inFile().nextLine(); // for flushing

答案 1 :(得分:0)

nextLine()返回单个字符串。

考虑第一次迭代,例如&#34;圣诞派对&#34;。

如果您将此字符串拆分为\n,那么您将获得的是#34;圣诞派对&#34;在长度为1的数组中。按&#34; 空格&#34;它应该工作。

答案 2 :(得分:0)

您可以创建HashMap并在迭代期间将所有选项放入其中。

HashMap<String, Integer> hmap = new HashMap<>();

while (sc.hasNext()) {
      String name = sc.nextLine();
      int tickets = Integer.parseInt(sc.nextLine());
      hmap.put(name, tickets);
}

现在,您可以使用HashMap中的每个条目执行所需操作。

注意:这假设您已对文本文件的第一行(示例中的4)执行了某些操作。

相关问题