繁体   English   中英

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

[英]Java, Reading two different types of variables from a file and using them as objects later

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

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

  • 4
  • 圣诞晚会
  • 20
  • 情人节
  • 12
  • 复活节
  • 万圣节
  • 8

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

例如,圣诞晚会有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;

    } 

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

谢谢

str仅包含聚会名称,将其拆分将不起作用,因为那里没有'\\ n'。

在循环中应该是这样的:

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

Party party = new Party(name, tickets);

// Print it here.

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

nextLine()返回一个字符串。

考虑第一次迭代,例如“圣诞节派对”。

如果将此字符串除以\\n您将得到的是长度为1的数组中的“圣诞节派对”。除以“ 空格 ”,它将正常工作。

您可以创建一个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行)做了一些操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM