简体   繁体   English

在Java中,使用扫描仪从.txt文件中读取数据,以便我可以使用该数据作为构造函数参数来生成对象

[英]In Java, using a Scanner to read in data from a .txt file so I can generate objects with that data as constructor parameters

I have a .txt file with content that has the following format: 我有一个.txt文件,其内容具有以下格式:

Car
300
1

Basically, the first line is the Expense object's name, the second line is the Expense object's cost, and the third line is the Expense object's frequency. 基本上,第一行是Expense对象的名称,第二行是Expense对象的成本,第三行是Expense对象的频率。 My text file is repetitions of three lines following that format. 我的文本文件是该格式后三行的重复。 I'm able to use a Scanner to store all these lines into a list but for some reason, my code isn't generating the Expense objects correctly. 我可以使用扫描仪将所有这些行存储到列表中,但是由于某些原因,我的代码无法正确生成Expense对象。 When creating an Expense object, my constructor takes string expenseName, int expenseCost, and int expenseFreq as arguments. 在创建Expense对象时,我的构造函数将字符串ensemName,intenseCost和intexpenseFreq用作参数。 However, after debugging I noticed that my output was strange because it appears the Scanner is reading everything from the .txt file as if it's a string even if I want it to be stored as an integer. 但是,在调试之后,我注意到我的输出很奇怪,因为即使我希望将其存储为整数,扫描程序仍似乎正在从.txt文件读取所有内容,就像是字符串一样。 Here is the code: 这是代码:

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;

    public class readInFile {

        static ArrayList list = new ArrayList();
        static String expenseName;
        static int expenseCost;
        static int expenseFreq;

        public static void main(String[] args){
            File file = new File("C:/Practice/expenses.txt");
            ArrayList fileContents = new ArrayList();
            int count = 0;
            int makeExpenseObject = 0;

            try {
                Scanner input = new Scanner(file);

                while(input.hasNext()){
                    fileContents.add(input.nextLine());
                }

                for (Object o: fileContents){
                    if (makeExpenseObject == 3){
                        Expense e = new Expense(expenseName, expenseCost, expenseFreq);
                        makeExpenseObject = 0;
                        list.add(e);
                    }

                    if (o instanceof String){
                        expenseName = o.toString();
                        makeExpenseObject++;
                    }

                    else if (o instanceof Integer && count == 0){
                        expenseCost = (int)o;
                        count++;
                        makeExpenseObject++;
                    }
                    else if (o instanceof Integer && count != 0){
                        expenseFreq = (int)o;
                        count = 0;
                        makeExpenseObject++;
                    }
                }
            }
            catch (FileNotFoundException e) {
                System.out.println("File not found.");
            }

            for (Object o: list){
                Expense e = (Expense) o;
                System.out.println(e.getName() + ", " + e.getCost() + ", " + e.getFreq());
            }

        }
    }

I was thinking of trying a BufferedReader instead of a Scanner but this should be working as far as I can tell. 我当时正在考虑尝试使用BufferedReader而不是Scanner,但据我所知,这应该可以工作。 I tried keeping a counter as the file was being scanned and the lines added to a list. 在尝试扫描文件并将行添加到列表时,我尝试保持计数器。 Whenever the counter was zero, I would use Scanner's nextLine method. 每当计数器为零时,我都将使用Scanner的nextLine方法。 Whenever the counter was not zero, I'd use Scanner's nextInt method and I'd reset the counter to zero if it was ever equal to 2. This didn't work either - it appears that the Scanner was still seeing that the contents of the file were all strings. 每当计数器不为零时,我都会使用Scanner的nextInt方法,如果计数器等于2,则将其重置为零。这也不起作用-看来Scanner仍在看到该文件都是字符串。 Why is this? 为什么是这样?

The goal of this code is to make a simple expense tracking app for fun. 此代码的目的是使一个简单的费用跟踪应用变得有趣。 I want to add my expenses to a .txt file and have the code read the file. 我想将费用添加到.txt文件中,并让代码读取该文件。 Before, I was using the code in a console application but it gets tedious typing in my expenses every time I use the app. 以前,我在控制台应用程序中使用代码,但是每次我使用该应用程序时,输入我的花费都很麻烦。 Right now I want to add the .txt reading functionality and eventually a GUI. 现在,我想添加.txt阅读功能,并最终添加一个GUI。 Thanks for any suggestions. 感谢您的任何建议。

When you read in the data from the file why don't you just assign it to the correct variables? 当您从文件中读取数据时,为什么不将其分配给正确的变量呢? Then parse the variables using the Integer.parseInt(String s) method. 然后使用Integer.parseInt(String s)方法解析变量。

I Am still a student, but i think that you have to change the way u view the problem...try to assign every first line to the string member of ur class and the second to the int and the third to the int. 我仍然是一名学生,但是我认为您必须改变您看问题的方式...尝试将每一行分配给ur类的字符串成员,将第二行分配给int,将第三行分配给int。 for this u can use a for loop from 1 to 3 and three if statements 为此,您可以使用从1到3的for循环和三个if语句

Hope I helped you 希望我能帮助你

The reason you are having issues with scanner.nextLine() is because nextLine() returns a String, more info. 您有问题的原因scanner.nextLine()是因为nextLine()返回一个字符串, 更多信息。

Try this: 尝试这个:

public class readInFile {

    public static void main(String[] args){

       ArrayList list = new ArrayList();                

        File file = new File("C:/Practice/expenses.txt");
        ArrayList<String> fileContents = new ArrayList();

        try {
            Scanner input = new Scanner(file);

            while(input.hasNext()){
                fileContents.add(input.nextLine());
            }


          for (int i=0; i< fileContents.size()-3; i++){

      String expenseName = fileContents.get(0);
      int expenseCost = Integer.parseInt(fileContents.get(1)) ;
      int expenseFreq = Integer.parseInt(fileContents.get(2));

      Expense e = new Expense(expenseName, expenseCost,expenseFreq);                             
       list.add(e);

            }
        }

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

相关问题 尝试读取文件时出现 Java.lang.NumberFormatException,因此我可以将数据用于我的对象 - Java.lang.NumberFormatException when trying to read in a file, so I can use the data with my objects 从 .txt 文件中读取特定数据 JAVA - Read specific data from a .txt file JAVA 使用扫描仪读取文件数据 - Read file data using Scanner 使用扫描程序和JAVA中的多个分隔符从文本文件中读取数据 - Read data from text file with scanner and multiple delimiters in JAVA 如何更改txt文件中的数据(字符串)以便我可以对该数据进行数学运算? - How to change data(string) from a txt file so I can do mathematical operations on that data? 用于打开和读取 Java 中数据的文件和扫描器对象 - File and Scanner objects for opening and reading data in Java Java-如何使用bufferedReader和Scanner将数据读入列表? - Java - How do I read data into a list using bufferedReader and Scanner? 在Eclipse(Java)中无法使用Scanner读取txt文件 - Can't read txt file with Scanner in Eclipse (Java) 如何从.txt文件中读取对象的某些分组属性并用Java计算它们的总数? - How can i read certain grouped attributes of objects from a .txt file and calculate their totals in Java? 如何使用扫描仪从命令行读取文件 - How can I read a file from the command line using scanner
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM