简体   繁体   中英

How to read information from file and put it back into String array?

I have a task where I need to read information form a file. Format of information in a file is: London Moscow .... I have 7 cities and 7 rows in total. I need to read names of cities and put them back in a String array. When I test this piece of code i get a message java.lang.ArrayIndexOutOfBoundsException: 0 .

I will appreciate any ideas on how I can fix the issue.

import java.util.Scanner;
import java.io.*;
public class Input {

        static Scanner keyboard, input;
        static PrintWriter output;
        static String[] namesCities;
        static String name = ""; 
        static int index;

        public static void main(String args[]) {

            try
{
            System.out.println("Please, enter the name of input file");
            keyboard = new Scanner(System.in);
            name = keyboard.nextLine();

            File file = new File(name);
            input = new Scanner(file);

            namesCities = new String[index];

            for (int index = 0; index < 7; index++) 
            {
                namesCities[index] = input.next();
            }
}
catch 
{

 catch (IOException a)

     { 
        System.out.println("Could not find file " + name);
        name = keyboard.nextLine();                       
    }
}
}

In your existing code, you haven't properly initialized index variable due to which its value remains zero and your namesCities = new String[index]; results in zero size array which results into ArrayIndexOutOfBoundsException . You need to initialize it to 7 like namesCities = new String[7];

Avoid declaring variables at class level whose scope shouldn't last longer than needed. Like Scanner object or filename in your code, doesn't seem to have any value living long in fact if not properly managed, they may lead to resource leakage. Try this code which reads your file using Files.readAllLines in one line and returns as a List object where each item in list contains your line in the file. Then you can convert it to array using toArray .

public static void main(String[] args) throws Exception {
    System.out.println("Please, enter the name of input file");
    Scanner keyboard = new Scanner(System.in);
    String name = keyboard.nextLine();
    keyboard.close();

    List<String> lines = Files.readAllLines(Paths.get(name));
    String[] nameCities = lines.toArray(new String[lines.size()]);
    System.out.println(Arrays.toString(nameCities));
}

Let me know if you have trouble understanding any of the code here.

So I wrote up something small. This assumes you already did all the proper imports and does no actual checking to make sure the file is the right size. If you absolutly must use a for loop you can change my loop to a for loop that goes tell counter < 7 (not counter <= 7)<---This will throw an index error.

I changed a few things but feel free to change them back, I moved the variables inside main because you gave no reason that they should stay as instance variables. I also changed your .nextLine() to .next() the reason is because .nextLine() cosumes everything tell it hits a new line character while .next() only goes tell it hits a white space character. You can change both of these back to the way you had it if that is the behavior you were going for.

public class Input{
    public static void main(String[] args){
        System.out.println("Please Enter the name of the input file");
        keyboard = new Scanner(System.in);
        name = keyboard.next();

        File file = new File(name);
        input = new Scanner(file);

        String[] nameCities = new String[7];
        int counter = 0;
        while(input.hasNext()){
            nameCities[counter] = input.next();
            counter++;
        }
        keyboard.close()//don't forget to close your scanner
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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