简体   繁体   中英

Issues with While loop condition

I am writing a program that reads a text file which contains match results, and then should output them in a table. I have a While loop within a While loop:

Scanner fileread1 = new Scanner(new File("demo.txt"));
int x = 0;
int y = 22;
int i = 0;
while (x <= y) {

    while (fileread1.hasNext()) {
    fileinput = fileread1.nextLine(); // this reads the next line of

    // from the file
    String line = fileinput;
    String[] split = line.split(":");
    boolean result = false;
    int homescore1 = 0;
    int awayscore1 = 0;
    int goalsscored = 0;
    boolean att = false;
    boolean htt = false;
    int atscore = 0;
    int htscore = 0;

    // When the text line is read, it is then split into four sections.

    if (split.length == 4) {

        // String text = line.trim();
        String userteam = userteaminput;
        String hometeam = split[0].trim();
        String awayteam = split[1].trim();
        String home_score = split[2].trim();
        String away_score = split[3].trim();

        // this is a test to try convert the goals string into a
        // integer. If this fails, the result is not
        // not valid and does not get outputted to the console.
        try {
            homescore1 = Integer.parseInt(home_score);
            awayscore1 = Integer.parseInt(away_score);
            result = true;
        }

        catch (NumberFormatException exception) {
            // if the try is not able to convert, this will run
            errors++;
        }


        if (userteam.equals(Teams.get(i))) {

            if (awayteam.equalsIgnoreCase(userteam)) {
                att = true;
                games++;
                goalsfor = goalsfor + awayscore1;
                goalsagainst = goalsagainst + homescore1;
            }

            if (att == true && awayscore1 > homescore1) {                                                                   
                atwc++;
                gameswon++;
            }

            else if (att == true && awayscore1 < homescore1) {
                htwc++;
                gameslost++;
            }

            else if (att == true && awayscore1 == homescore1) {
                gamesdrawn++;
            }

            if (hometeam.equalsIgnoreCase(userteam)) {
                htt = true;
                totaluser++;
                games++;
                goalsfor = goalsfor + homescore1;
                goalsagainst = goalsagainst + awayscore1;

            }

            if (htt == true && homescore1 > awayscore1) {                                   
                atwc++;
                gameswon++;

            }

            else if (htt == true && homescore1 < awayscore1) {
                htwc++;
                gameslost++;
            }

            else if (htt == true && awayscore1 == homescore1) {
                gamesdrawn++;
            }
        } 
    }
        else {
            errors++;

        }
    }

        // ********************************************************************
        // Leeds IF Statement
        // ********************************************************************
        if (Rhinos.equals(Teams.get(i)) {
            Rhinos.goalsfor = Rhinos.goalsfor + goalsfor;
            Rhinos.gameswon = Rhinos.gameswon + gameswon;
            Rhinos.gameslost = Rhinos.gameslost + gameslost;
            Rhinos.goalsagainst = Rhinos.goalsagainst; 
            Rhinos.gamesplayed = Rhinos.gamesplayed + games; 
        }
          else if (Bulls.equals(Teams.get(i)) {
            Bulls.goalsfor = Bulls.goalsfor + goalsfor;
            Bulls.gameswon = Bulls.gameswon + gameswon;
            Bulls.gameslost = Bulls.gameslost + gameslost;
            Bulls.goalsagainst = Bulls.goalsagainst; 
            Bulls.gamesplayed = Bulls.gamesplayed + games;
        } 
        x++;
        i++;
        goalsfor = 0;
        gameswon = 0;
        gameslost = 0;
        gamesagainst = 0;
        }

I know that there are only ever going to be 22 teams that have results in the text file supplied, so the first loop should run for 22 times.

The inner loop, will continue whilst the file provided has a next line. The text file may sometimes have more lines of results then other files. Within this loop, I have a reference to an Array item:

if (userteam.equals(Teams.get(i)))

In the first run, this will refer to 0 in my Array which, for the record, is Leeds Rhinos. Once the inner loop has completed, it then moves onto the outer loop - this deals with the results just recorded. If the current team is Leeds Rhinos, it should then add the values. The i should then have 1 added, so for the next loop, it refers to the index of 1 of the array, not 0. (I have more IF statements here, all identical but refer to other teams) Variables get set back to 0, ready for the next run.

The issue I have, is that i does not seem to have 1 added each time it runs through, so I am only getting results passed through for one team. If I manually specify which array index to look (say 3) it will run through, and the team will have their results successfully recorded.

Is there a way I can get 1 added to i every time it loops? I'm not sure if this is the correct java loop to use, but to me, seemed the most logical. There are some objects not declared here - this is just a snippet of the code, left out the declarations as I know they work, and there's a lot declared.

If you're worried about failed incrementation, it would be better to use a For loop.

Instead of having a while (x < y) and sticking an increment statement somewhere in your code, a

for (i = 0; i < y; i++) { // do tests here }

loop will guarantee that you always increment and run the test for the next team.

For future reference, when using while loops and incrementing, the incrementation is almost always done at the END of the while loop, and not somewhere in between. The incrementation statement should also almost never be in a conditional statement (which might cause an infinite loop).

Your question is not clear. But let's point out something in the code you provided

1) What is the difference between your if and else if statement? They are checking exact same thing

if (userteam.equals(Teams.get(i)) {
     Rhinos.goalsfor = Rhinos.goalsfor + goalsfor;
     Rhinos.gameswon = Rhinos.gameswon + gameswon;
     Rhinos.gameslost = Rhinos.gameslost + gameslost;
     Rhinos.goalsagainst = Rhinos.goalsagainst; 
     Rhinos.gamesplayed = Rhinos.gamesplayed + games; 
}
else if (userteam.equals(Teams.get(i)) {
     Bulls.goalsfor = Bulls.goalsfor + goalsfor;
     Bulls.gameswon = Bulls.gameswon + gameswon;
     Bulls.gameslost = Bulls.gameslost + gameslost;
     Bulls.goalsagainst = Bulls.goalsagainst; 
     Bulls.gamesplayed = Bulls.gamesplayed + games;
} 

2) What are you doing with variable x, I don't see anywhere you are increasing it.

3) On very first run, when x<=y, the inner loop will finish reading all lines, so even if you increase the X some point, from second run the inner loop will not execute. As it already finished reading all lines. So no point doing this

Again if you provide some more inside on what you want to accomplish, may be with the sample text file data, that would probably help answering your question.

Thank you.

Your formatting is working against you here; properly indented, your code structure is something like this (note, I had to add in missing closing braces, } , at the end of the code you provided as I assume you just missed them when you copied your code over):

Scanner fileread1 = new Scanner(new File("demo.txt"));
int x = 0;
int y = 22;
int i = 0;
while (x <= y) {
    while (fileread1.hasNext()) {
        fileinput = fileread1.nextLine(); // this reads the next line of

        /* stuff */

        if (split.length == 4) {

            /* stuff */

            x++;
            i++;
        }
    }
}

Your incrementation of x and i is nested within if (split.length == 4) { , meaning that x and i will only be incremented in that specific case and not at the end of each iteration of the inner while loop.

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