0

嗨,我正在尝试慢慢学习 Java,但我遇到了无限循环的问题。下面是我的代码。从构造函数开始到显示方法结束,如何在添加最后一个条目后停止循环?

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++;
    }
}

感谢您对此的任何帮助!

4

1 回答 1

2

索引++;line 不是必需的,实际上可能是您无限循环的原因。index++ 已在 for() 语句中指定。再次添加 is 意味着每个循环的索引都增加 2。

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

}
于 2012-12-09T21:04:05.483 回答