简体   繁体   中英

Infinite loop cant figure out how to stop it java

Hi, I'm trying to learn Java slowly, but I'm having trouble with a infinite loop. Below is my code. From the start of the constructor until the end of the display method, how do I go about making the loop stop after the last entry added?

public UnitResults(int Size, String title)
{            
    this.fName = new String [Size];
    this.surname = new String [Size];
    this.Marks = new int [Size];
    pointer = 0;

    fName[pointer] = "Daniel";
    surname[pointer] = "Scullion";

    Marks[pointer] = 60;
    unitTitle  = title;

    pointer ++;

}

public Boolean add( String tempfName, String tempsName, int newGrade)
{ 
    if (pointer == fName.length)
    {
    System.out.println("The Students Database is full");
    return false;
    }
    else
    { 
        fName [pointer] = tempfName;
        surname [pointer]  = tempsName;
        Marks[pointer] = newGrade;
        pointer ++;
        System.out.println("Student Added");
        return true;
    }
} // end Add

public void display()
{
    System.out.println("Students Results\n");
    for (int index = 0; index < pointer; index++)
    {
        System.out.println( unitTitle + "\n" 
            + fName[index] + "\n"  
            + surname[index] + "\n" 
            + Marks[index] + "\n"
            + "\n" );  
        index++;
    }
}

Thanks for any help with this!

The index++; line is not required and indeed is probably the cause of your infinite loop. The index++ is already specified in the for() statement. Adding is again means that index is incremented by 2 for each loop.

for (int index=0; index < pointer;  index ++)
{

    System.out.println( unitTitle + "\n" 
            + fName[index] + "\n"  
            + surname[index] + "\n" 
            + Marks[index] + "\n"
            + "\n" );  
    index++; // <<<----- this line should not be here

}

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