Domanda

I need to fill the two seperate arrays with the names from a text file and corresponding account balances. The file looks like this

10
Helene 1000
Jordan 755
Eve 2500
Ken 80
Andrew 999
David 1743
Amy 12
Sean 98
Patrick 7
Joy 14

where 10 is the number of accounts

import java.util.*;
import java.io.*;
import java.util.Arrays;

public class bankaccountmain {

    public static void main(String[] args) throws FileNotFoundException {
        Scanner inFile = null;
        try {
            inFile = new Scanner(new File("account.txt"));
            ;
        } catch (FileNotFoundException e) {
            System.out.println("File not found!");

            System.exit(0);
        }
        int count = 0;
        int accounts = inFile.nextInt();
        String[] names = new String[accounts];
        int[] balance = new int[accounts];
        while (inFile.hasNextInt()) {
            inFile.next();
            names[count] = inFile.next();
            inFile.nextInt();
            balance[count] = inFile.nextInt();
            count++;
        }
        System.out.println(Arrays.toString(names));
        System.out.println(Arrays.toString(balance));
    }
}
È stato utile?

Soluzione

Your loop is poorly defined.

You are checking to see if there is a next int instead of a next token, and consuming lines you don't intend to.

Try this as a loop instead:

    while (inFile.hasNext()) {
        names[count] = inFile.next();
        balance[count] = inFile.nextInt();
        count++;
    }

Altri suggerimenti

Change the loop as follows. Change the while() clause and comment out the 2 lines.

    while (inFile.hasNext()) {
        //inFile.next();
        names[count] = inFile.next();
        //inFile.nextInt();
        balance[count] = inFile.nextInt();
        count++;
    }

This

int accounts = inFile.nextInt();

consumes this token

10

You then do

while (inFile.hasNextInt()) {

but the next tokens in the file are

\nHelene 1000

so the method call will return false since there is no next int and the loop will exit.

Perhaps you should check for full lines.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top