如何将文件循环到数组并在循环中创建新对象?

时间:2017-11-12 03:07:38

标签: java

我在eclipse中创建了一个名为Soda的新公共类,它包含以下私有数据字段:name(String),price(double),quantity(integer)和盎司(integer)。

每个数据字段都有setter(访问器)和getter(mutators)。价格,数量的制定者, 如果向它们发送负值,则盎司会保持关联的数据字段不变。

名为reduce的公共方法,仅从数量数据字段中减去金额(参数) 如果数量大于或等于金额且金额为正数。该方法没有 返回一个值。

在我的名为popMachine的主类中,我应该将文件中的苏打水读入流行机器(一系列苏打水对象),减少苏打水的数量。 机器,然后将苏打信息写回另一个文件。在这部分我应该打开文件进行阅读,并将每个苏打水读入数组  当没有更多的线要处理或者处理时停止阅读  数组充满了苏打水。

在每次循环迭代中,我需要添加一个新的Soda  对象到数组,获取与之关联的4行数据  苏打水,并用该数据设置苏打水对象。

    public static int fillMachine(Soda[] popMachine,
 String fileName) throws IOException
 {
   Soda soda1 = new Soda();
   fileName = "Sodas.txt";
   File file = new File(fileName);
   if(!file.exists()) {
     System.out.print("File Open Error: " + file.getName());
     System.exit(1);
   }
//my problem is here in the loop I don"t know where to continue or how to loop through the rest of the file
   Scanner input = new Scanner (new File (fileName));
   while (input.hasNextLine()){
     for(int i = 0; i < fileName.length(); i++) {
       for(int j = 0; j < fileName.length(); j++) {
         popMachine[i] = soda1.setName(j) +
                         soda1.setPrice(j + 1) +
                         soda1.setQuantity(j + 2) +
                         soda1.setOunces(j + 3);
       }
     }

   }
 }

1 个答案:

答案 0 :(得分:0)

s要从文件中获取一行数据作为字符串,您可以使用Scanner的nextLine函数。然后,您可以使用此字符串执行任何操作。

现在不知道您所说的这个文本文件的确切布局,以下是我可以帮助您的方法。

假设您有一个文本文件,其内容如下所示:

Hello
2
0.14
Hi
4
0.92

你知道的是每1/3行是一个字符串,每2/3行是一个int,每3行是一个double。 所以你要做这样的事情来在数组中创建一个新的苏打对象,并根据这些行设置它的变量。您可能需要针对您的需求进行一些调整,但我认为这可以提供帮助:

Scanner scanner = new Scanner (new File (fileName));

    for(int j = 0; scanner.hasNextLine(); j++) {
        popMachine[j] = new Soda();
        for(int i = 1; i <= 3; i++) {
            String line = scanner.nextLine();
            if(i == 1) {
                popMachine[j].setName(line);
            } else if(i == 2) {
                popMachine[j].setOunces(Integer.parseInt(line));
            } else if(i == 3) {
                popMachine[j].setPrice(Double.parseDouble(line));
            }
        }
    }

(不要忘记用scanner.close()关闭扫描仪;)

显然,这不是一个完美的答案,并不是完全可以防止错误的,但这是我能用最有限的材料和一些令人困惑的问题给你的最佳答案。

编辑:您可以通过集成两个for语句来进一步简化我的代码段:

        for(int i = 1; scanner.hasNextLine();) {
            String line = scanner.nextLine();
            if(i % 3 == 1) { // These make sure it's every 1/3, 2/3, 3/3 line etc. Plugging in 1 % 3 will give one, 4 % 3 is one, etc.
                popMachine[j].setName(line);
                i++;
            } else if(i % 3 == 2) { // 2 % 3 is 2, 5 % 3 is 2.
                popMachine[j].setOunces(Integer.parseInt(line));
                i++;
            } else if(i % 3 == 0) { // You get the gist
                popMachine[j].setPrice(Double.parseDouble(line));
                i++;
                j++;
                popMachine[j] = new Soda();
            }

        }
相关问题