簡體   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