简体   繁体   中英

While Loop Not Entering When Condition is True

I'm creating a Method which will read a file and return an arrayList of Person (a class that I made). In this method I currently have two while loops(each with their own try/catch). The first runs perfectly, but the second one doesn't seem to enter the loop even though the condition is true. Here is my code:

public static ArrayList <Person> read(String fileName)
{
    int counter = 0;
    ArrayList <Person> persons = new ArrayList <Person> ();
    ArrayList <String> temp = new ArrayList <String> ();
    ArrayList <String> tempTwo = new ArrayList <String> ();

    try
    {   
        Scanner inputFile = new Scanner(new FileReader(fileName));
        String unusedLine = inputFile.nextLine();
        String name = inputFile.nextLine();


        while(inputFile.hasNextLine())
        {
            unusedLine = inputFile.nextLine();
            String tempDate = inputFile.nextLine();
            temp.add(tempDate);
            String tempWeight = inputFile.nextLine();
            temp.add(tempWeight);
            unusedLine = inputFile.nextLine();

            counter += 2; //one for each entry
            //System.out.println("counter: " + counter);

        }
    }
    catch(Exception e)
    {
        System.out.println(e.getMessage());
    }

    try
    {
        counter += 1; // one for name
        System.out.println(counter);

        while(counter > 0)
        {
            String tempString = temp.get(counter);
            //System.out.println(tempString);
            int start = tempString.indexOf('>');
            System.out.println(start);
            int end = tempString.indexOf('<', start);
            System.out.println(end);
            String subStringTemp = tempString.substring(start, end);
            System.out.println("parsed: " + subStringTemp);
            temp.add(subStringTemp);


            counter --;

        }
    }
    catch(Exception f)
    {
        System.out.println(f.getMessage());
    }





    return(null);//just so it compiles

The file type that I am reading from is xml and will look something like this:

<person>
    <name>name</name>
    <entry>
        <date>10.12.14</date>
        <weight>172.1</weight>
    </entry>
</person>

The Print Statement in the second loop, prints nothing:

No line found           //first catch prints this exception
10                      //value of counter before second loop
Index: 10, Size: 10     //I don't know what this is

Why is my while loop never being entered?

Edit: I had forgotten to add name to my ArrayList so it was of size 10 when I had already accounted in counter for it to be of size 11. Thanks to everyone for helping me think about it in the right way!

Its throw IndexOutOfBoundsException at line:

String tempString = temp.get(counter);

Default capacity of ArrayList is 10

You have a list of 10 objects. To iterate that list with an index, which is what you are doing with temp.get , you will call temp.get(0) through temp.get(9) . But when you enter the second while-loop, you are calling temp.get(10) , which doesn't exist. What you should be doing is temp.get(counter - 1) and change the while-clause to while(counter >= 0)

I would like to emphasize dasblinkenlight's point that this is a terrible method to parse XML. If your task is to parse an XML string and print out it's objects, I would recommend you Google specifically how to do that.

Setting aside the quality of the parser, the code seems to enters the second loop but the first line of the loop body throws an index of out bounds exception (and you are seeing "Index: 10, Size: 10" printed as per catch section). The arrays have a zero-based index, so if after the first loop the counter value is N, if the intention is to read the last element in the second loop, it should be N-1.

String tempString = temp.get(counter - 1);

This may or may not help, because there is another issue. You increment the counter by 1 (with a comment that it is to handle "name" but the name value never added to the array) before the second loop that even more contributes to the index problem. There is more, in the second loop you seem to read the values, parse the data and put the parsed data back to the same array list. Not sure what is the expected result. A simple unit test would discover these issues and after fixing the code it would serve for you for long time.

Also, as many suggested, it is not a recommended way to parse XML content. I strongly recommend using an XML parser.

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