简体   繁体   English

从外部文件读取行并将元素存储在数组中

[英]read lines from external file and store elements in array

I am new here so please show some patience. 我是新来的,请耐心等待。 I am trying to read the data from an external file and store the info in 2 arrays. 我正在尝试从外部文件读取数据并将信息存储在2个数组中。 The file looks like this: 该文件如下所示:

0069     723.50 
0085     1500.00
0091     8237.31

I am using 2 scanners to read the input and I think they work ok because when I try to print, the result looks ok. 我使用2台扫描仪来读取输入,我认为它们可以正常工作,因为当我尝试打印时,结果看起来还可以。 My first problem is that I am able to read the first numbers on the list using nextInt(), but cannot use nextDouble() for the double ones as I get the "java.util.InputMismatchException" message. 我的第一个问题是,我可以使用nextInt()读取列表中的第一个数字,但是当我收到“ java.util.InputMismatchException”消息时,不能对双精度数使用nextDouble()。 For that reason I read it as a String. 因此,我将其读取为字符串。 The part with the other two scanners is supposed to do what the first parts should do, for a different input file, but the problem is the same. 对于其他输入文件,应该使用具有其他两个扫描程序的部件来执行第一部分应该执行的操作,但是问题是相同的。 My next and biggest problem, until now, is that am not able to store the values from the two columns in two distinct arrays. 到目前为止,我的下一个也是最大的问题是无法将两个列中的值存储在两个不同的数组中。 I have tried several ways (all commented) but all fail. 我尝试了几种方法(全部已评论),但都失败了。 Please help and thanks. 请帮忙,谢谢。 Here is my code: 这是我的代码:

import ui.UserInterfaceFactory;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.Scanner;
import ui.UIAuxiliaryMethods;

public class Bank {
    static final int MAX_NUMBER_OF_ACCOUNTS = 50;

    PrintStream out;

    Bank(){
        UserInterfaceFactory.enableLowResolution(true);
        out = new PrintStream(System.out);
    }

    void readFiles(){
        Scanner balanceFile = UIAuxiliaryMethods.askUserForInput().getScanner();
        while(balanceFile.hasNextLine()){
            String balance_Line = balanceFile.nextLine();
            Scanner accountsFile = new Scanner(balance_Line);

            int account = accountsFile.nextInt();                       //works
            out.printf("%04d ",account);


            /*int [] accounts_array = new int [MAX_NUMBER_OF_ACCOUNTS];         //does not store the values properly
            int account = accountsFile.nextInt();
            for(int j=0; j < accounts_array.length; j++){

                accounts_array[j] = account;

            }*/

            /*int [] accounts_array = new int [MAX_NUMBER_OF_ACCOUNTS];         //java.util.InputMismatchException
                for(int j=0; j < accounts_array.length; j++){

                    accounts_array[j] = accountsFile.nextInt();
                    //out.printf("%04d \n",accounts_array[j]);
                }*/


            String balance = accountsFile.nextLine();                       //problem declaring balance as a double
            out.printf("%s\n",balance);

            /*String [] balance_array = new String [MAX_NUMBER_OF_ACCOUNTS];            //java.util.NoSuchElementException
            for(int j=0; j < balance_array.length; j++){
                accountsFile.useDelimiter(" ");

                balance_array[j] = accountsFile.next();
                //out.printf("%04d \n",accounts_array[j]);
            }*/
        }

        Scanner mutationsFile = UIAuxiliaryMethods.askUserForInput().getScanner();
        while(mutationsFile.hasNext()){

            String mutation_Line = mutationsFile.nextLine();
            Scanner mutatedAccountsFile = new Scanner(mutation_Line);


            int mutated_account = mutatedAccountsFile.nextInt();
            out.printf("%04d ",mutated_account);


            int action = mutatedAccountsFile.nextInt();     //deposit or withdrawal
            /*if (action == 1){

            }else{

            }*/
            out.printf(" %d ",action);

            /*Double amount = mutatedAccountsFile.nextDouble();
            out.printf(" %5.2f ",amount);*/
            String amount = mutatedAccountsFile.nextLine();
            out.printf("%s\n",amount);
        }

    }

    void start(){
        new Bank();readFiles();
    }


    public static void main(String[] args) {
        new Bank().start();
    }
}   

The InputMismatchException occurs because you try to read a double using the nextInt() function. 发生InputMismatchException原因是,您尝试使用nextInt()函数读取一个double。 To solve this issue, you can first read the tokens as Strings using the next() function and convert them appropriately. 要解决此问题,您可以首先使用next()函数将标记读取为字符串, next()对其进行适当的转换。

while(mutationsFile.hasNext()){
    mutation_Line = mutationsFile.next();
    if(mutation_Line.indexOf(".") == -1)
        //token is int
    else
        //token is double
}

Since you already know what the contents of the two columns are, you can store the integers and doubles in two lists and then, if you want, get them into an array. 由于您已经知道两列的内容,因此可以将整数和双精度数存储在两个列表中,然后根据需要将它们放入数组中。

List<Integer> intList = new ArrayList<Integer>();
List<Double> doubleList = new ArrayList<Double>();

Now replace the if statements in the first snippet with this: 现在,用以下代码替换第一段中的if语句:

if(mutation_Line.indexOf(".") == -1)
    intList.add(new Integer(Integer.parseInt(mutation_Line)));
else
    doubleList.add(new Double(Double.parseDouble(mutation_Line)));

In the end, you can get them into arrays: 最后,您可以将它们分成数组:

Object[] intArr = intList.toArray(),
         doubleArr = doubleList.toArray();
//display the contents:
for(int i=0; i<intArr.length; i++)
out.printf("%04d\t%.2f\n", Integer.parseInt(intArr[i].toString()),
                       Double.parseDouble(doubleArr[i].toString()));

OUTPUT : 输出

0069    723.50
0085    1500.00
0091    8237.31

First off, you don't need to use 2 scanners. 首先,您不需要使用2台扫描仪。 The Scanner object is simply reading your file, one scanner is plenty to accomplish the task of reading a file. 扫描程序对象只是读取文件,一个扫描程序足以完成读取文件的任务。

If you're trying to read the integers/doubles from file and are having trouble with nextInt() and nextDouble(), consider a different approach to parsing (eg parse the line into a string, split the line into 2 parts based on a space character, then trim both resulting strings and convert to respective integers/doubles). 如果您尝试从文件中读取整数/双精度数,并且在使用nextInt()和nextDouble()时遇到麻烦,请考虑采用另一种解析方法(例如,将行解析为字符串,将行拆分为2部分)。空格字符,然后修剪两个结果字符串并转换为相应的整数/双精度数)。

Now back to the Scanner parsing the two values, remember first that when you use a next() or nextInt(), etc. those methods consume the next respective token. 现在回到扫描器解析这两个值,首先要记住,当您使用next()或nextInt()等时,这些方法会消耗下一个各自的标记。 So parsing a line as a string from the file into another Scanner object is redundant and unnecessary in this case. 因此,将行作为文件中的字符串解析为另一个Scanner对象是多余的,在这种情况下是不必要的。

If you know your max number of accounts, and it's simply 50, then go ahead an allocate that prior to the while loop. 如果您知道最大帐户数(也就是50),那么请在while循环之前进行分配。

Here's an alternative approach with the code you posted. 这是您发布的代码的另一种方法。

public class App {
    static int MAX_NUMBER_OF_ACCOUNTS = 50;
    static PrintStream out;
    static void readFiles() {
        Scanner balanceFile = null;
        try {
            balanceFile = new Scanner(new File("C:\\Users\\Nick\\Desktop\\test.txt"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        if (balanceFile == null)
            return;
        int [] accounts_array = new int [MAX_NUMBER_OF_ACCOUNTS];
        double [] balance_array = new double [MAX_NUMBER_OF_ACCOUNTS];
        int currentIndex = 0;
        while (balanceFile.hasNextLine()) {
            int account = balanceFile.nextInt();
            double balance = balanceFile.nextDouble();
            System.out.print("acc = " + account + " ");
            System.out.println("bal = " + balance);
            //out.printf("%04d ", account);
            accounts_array[currentIndex] = account;
            //out.printf("%s\n", balance);
            balance_array[currentIndex] = balance;
            currentIndex++;
        }
        balanceFile.close();
    }
    static void start() {
        readFiles();
    }
    public static void main(String[] args) {
        start();
    }
}

Please note the excessive use of static could also be avoided in the future, but for the sake of the example it spread like the plague. 请注意,将来也可以避免过多使用静电,但是为了举例说明,它像瘟疫一样蔓延开来。

As you can see in the logic leading up to the while loop, the scanner object is made from a file I copied your example data into a file on my desktop. 正如您在导致while循环的逻辑中所看到的那样,scanner对象是由一个文件构成的,该文件是您将示例数据复制到桌面上的文件中的。 The arrays are allocated prior to the while loop (note: see @progy_rock and their use of ArrayList's - may help improve your code in the long run). 数组在while循环之前分配(注意:请参阅@progy_rock及其对ArrayList的使用-从长远来看可能有助于改善代码)。 And finally, note the index count to move the position along in the array to which you are inserting your lines to. 最后,请注意索引计数,以将位置插入行中的数组中。

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

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