简体   繁体   中英

Putting names from a file into an array is causing an infinite loop

I have a text file "names" which contains 10 names, each name on its own line. What I want to do is put these names into an array "anArray". Just to check that I'm doing an alright job, I outputted a line as you can see.

Here's the code I used to try to do that:

 public static void main(String[] args) throws FileNotFoundException
    { 
        File file=new File("names.txt");
        Scanner my_input= new Scanner(file);
        String [] anArray;
        anArray = new String[10];
        String a = my_input.nextLine();
        while(my_input.hasNextLine())
        {
            for(int i = 0; i<10;i++)
            {
                while (!(a.equals("\n")))
                {
                    anArray[i] = a;
                    System.out.println("Element" + i + "of the array is: " + anArray[i]);

                }
                i++;
                a=my_input.next();
            }
        }
        my_input.close();      
    }

However this code fails, what happens is "Element 0 of the array is: name 1" is outputted an infinite amount of times, "name 1" being the first name in the text file. I don't know what I'm doing wrong here, could anybody enlighten me?

The condition in the innermost while loop never changes, so the contents will repeat indefinitely.

Something to change the value of the phrase

while (!(a.equals("\n")))

must occur in the body of the loop, otherwise it will stay true if it starts out true.

You currently have an infinite loop on your inner while loop, you don't update a so that will loop forever once entered. I think you wanted to check that i is less than 10 and your input still has more lines. You can do that with a singe loop. I would also prefer a try-with-resources over explicitly closing. And you can guard against empty lines with String.isEmpty() . Something like,

File file = new File("names.txt");
try (Scanner my_input = new Scanner(file)) {
    String[] anArray = new String[10];
    for (int i = 0; i < 10 && my_input.hasNextLine(); i++) {
        String line = my_input.nextLine();
        if (line.isEmpty()) {
            continue;
        }
        anArray[i] = line;
        System.out.printf("Element %d of the array is: %s%n", i, anArray[i]);
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

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