簡體   English   中英

從外部文件讀取行並將元素存儲在數組中

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

我是新來的,請耐心等待。 我正在嘗試從外部文件讀取數據並將信息存儲在2個數組中。 該文件如下所示:

0069     723.50 
0085     1500.00
0091     8237.31

我使用2台掃描儀來讀取輸入,我認為它們可以正常工作,因為當我嘗試打印時,結果看起來還可以。 我的第一個問題是,我可以使用nextInt()讀取列表中的第一個數字,但是當我收到“ java.util.InputMismatchException”消息時,不能對雙精度數使用nextDouble()。 因此,我將其讀取為字符串。 對於其他輸入文件,應該使用具有其他兩個掃描程序的部件來執行第一部分應該執行的操作,但是問題是相同的。 到目前為止,我的下一個也是最大的問題是無法將兩個列中的值存儲在兩個不同的數組中。 我嘗試了幾種方法(全部已評論),但都失敗了。 請幫忙,謝謝。 這是我的代碼:

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();
    }
}   

發生InputMismatchException原因是,您嘗試使用nextInt()函數讀取一個double。 要解決此問題,您可以首先使用next()函數將標記讀取為字符串, next()對其進行適當的轉換。

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

由於您已經知道兩列的內容,因此可以將整數和雙精度數存儲在兩個列表中,然后根據需要將它們放入數組中。

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

現在,用以下代碼替換第一段中的if語句:

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

最后,您可以將它們分成數組:

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()));

輸出

0069    723.50
0085    1500.00
0091    8237.31

首先,您不需要使用2台掃描儀。 掃描程序對象只是讀取文件,一個掃描程序足以完成讀取文件的任務。

如果您嘗試從文件中讀取整數/雙精度數,並且在使用nextInt()和nextDouble()時遇到麻煩,請考慮采用另一種解析方法(例如,將行解析為字符串,將行拆分為2部分)。空格字符,然后修剪兩個結果字符串並轉換為相應的整數/雙精度數)。

現在回到掃描器解析這兩個值,首先要記住,當您使用next()或nextInt()等時,這些方法會消耗下一個各自的標記。 因此,將行作為文件中的字符串解析為另一個Scanner對象是多余的,在這種情況下是不必要的。

如果您知道最大帳戶數(也就是50),那么請在while循環之前進行分配。

這是您發布的代碼的另一種方法。

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();
    }
}

請注意,將來也可以避免過多使用靜電,但是為了舉例說明,它像瘟疫一樣蔓延開來。

正如您在導致while循環的邏輯中所看到的那樣,scanner對象是由一個文件構成的,該文件是您將示例數據復制到桌面上的文件中的。 數組在while循環之前分配(注意:請參閱@progy_rock及其對ArrayList的使用-從長遠來看可能有助於改善代碼)。 最后,請注意索引計數,以將位置插入行中的數組中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM