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

Java,从文件中读取两种不同类型的变量,然后将它们用作对象,java,arraylist,bufferedreader,filereader,Java,Arraylist,Bufferedreader,Filereader,我正在进行一个项目,该项目基于从文件中读取文本并将其作为对象放入代码中 我的文件包含以下元素: 忽略要点 4. 圣诞晚会 20 情人 12 复活节 5. 万圣节前夕 8. 第一行声明我的文本文件中有多少个party,顺便说一句 每个派对都有两行——第一行是名字,第二行是名额 例如,圣诞派对有20个名额 下面是我将文件中的信息保存为对象的代码 public class Parties { static Scanner input = new Scanner(System.in); p

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

我的文件包含以下元素: 忽略要点

4. 圣诞晚会 20 情人 12 复活节 5. 万圣节前夕 8. 第一行声明我的文本文件中有多少个party,顺便说一句 每个派对都有两行——第一行是名字,第二行是名额

例如,圣诞派对有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);
    }
有人能给我解释一下我如何处理这个错误吗

谢谢

下一行返回单个字符串

考虑第一次迭代,例如,圣诞派对


如果将此字符串拆分为\n,将得到长度为1的数组中的圣诞派对。按空格分割,它应该可以工作

str只包含参与方名称,拆分它将不起作用,因为其中没有“\n”

在循环中应该是这样的:

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

Party party = new Party(name, tickets);

// Print it here.

inFile().nextLine(); // for flushing
您可以创建一个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行做了一些操作。

您正在调用nextLine,然后在新行上拆分。这是行不通的-不应该有任何新行,因为您正在逐行解析。相反,请分别分析这些行。下一行返回一行,即不包含行分隔符的字符串。您要引用哪个下一行?因为我有两个感谢您的快速回复可能重复感谢您的回复,我改变了这一点,但是,我仍然得到这一行的错误:int tickets=Integer.parseInte[1];
HashMap<String, Integer> hmap = new HashMap<>();

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