Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
110 views
in Technique[技术] by (71.8m points)

java - Reading a File From the Computer

Now I have this error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4 at Lotto1.main(Lotto1.java:37)

Line 37: arr[count][0] = s.next() + ""+ s.next();

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

public static void main(String[] args) throws IOException  {

        File f = new File("D:\Filipe\Project Final\src\database_lotto.txt");
        Scanner s;
        try {
            s = new Scanner(f);

           BufferedReader reader = new BufferedReader(new FileReader(f));
            int lines = 0;
            while (reader.readLine() != null) {
                lines++;
            }
            reader.close();

            arr  = new String[lines][3];

            int count = 0;
            //while theres still another line
            while (s.hasNextLine()){
                arr[count][0] = s.next() + ""+ s.next();
                arr[count][1] = s.next();
                arr[count][2] = s.next();
               count++;                   
            }
        } catch (FileNotFoundException ex) {
           System.out.println("File does not exist");
        }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You didn't put the right path into the FileReader only into File f, you can pass f into the Filereader instead of repeating the path:

File f = new File("D:\database_lotto.txt");
[...]
BufferedReader reader = new BufferedReader(new FileReader(f));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...