在while循环中测试一个条件然后在Java

时间:2016-10-15 19:57:03

标签: java if-statement while-loop

我是Java的新手,我试图了解如何在for循环中嵌套if语句,并在执行if语句后让它退出for循环。我有一个数组,for循环遍历数组以查看是否存在ID,如果它应该删除它,如果它不存在那么它应该打印错误消息。发生的情况是条件是在while循环中的嵌套if语句中测试并打印错误消息3次。我希望它只打印一次错误消息。

在我的主要方法中我有

remove("3");
remove("3");

在第一个它应该删除该ID并打印它是rem,第二个它应该只打印错误消息一次。这是一个学校项目,不需要用户输入。我只是想了解如何在不打印重复错误消息的情况下完成这项工作

public static void remove(String studentID) 
{

    for (int i = 0; i < thestudents.size(); i++) 
    {

        Student temp = thestudents.get(i);

        if (temp.getStudentID()==(Integer.parseInt(studentID))) 
        {
            thestudents.remove(i);
            System.out.println("Student " + temp.getFirstName() + " was removed");
        }
        else
        {
            System.out.println("Student with ID " + studentID + " Was not found!");
        }
    }
}

结果:

Student with ID 3 Was not found!
Student with ID 3 Was not found!
Student Jack was removed
Student with ID 3 Was not found!
Student with ID 3 Was not found!
Student with ID 3 Was not found!
Student with ID 3 Was not found!
Student with ID 3 Was not found!

期望:

Student Jack was removed
Student with ID 3 Was not found!

3 个答案:

答案 0 :(得分:1)

只需在break语句中添加if即可。如果if语句为true,则循环将终止。

if (temp.getStudentID()==(Integer.parseInt(studentID))) {
    hestudents.remove(i);
    System.out.println("Student " + temp.getFirstName() + " was removed");
    break;
}

答案 1 :(得分:1)

您可以使用break语句来终止循环,或者更好的是,return语句一旦找到合适的项目就完全终止该方法:

public static void remove(String studentID) 
{

    for (int i = 0; i < thestudents.size(); i++) 
    {

        Student temp = thestudents.get(i);

        if (temp.getStudentID()==(Integer.parseInt(studentID))) 
        {
            thestudents.remove(i);
            System.out.println("Student " + temp.getFirstName() + " was removed");
            return;
        }
    }

    // If we get here it means we haven't returned, so the student wasn't found
    System.out.println("Student with ID " + studentID + " Was not found!");
}

答案 2 :(得分:0)

只需添加中断即可在匹配后删除输出,但匹配前的输出将保留。

我想你想要摆脱所有误判输出。

因此,您必须在循环之后移动负输出(这是else块的内容)(删除else行)并确保在ID为ID时不执行此代码找到。

执行此操作的最佳方法是在return块中添加if作为最后一个语句。

for (int i = 0; i < thestudents.size(); i++) 
{
    Student temp = thestudents.get(i);
    if (temp.getStudentID()==(Integer.parseInt(studentID))) 
    {
        thestudents.remove(i);
        System.out.println("Student " + temp.getFirstName() + " was removed");
        return; // leaving the method whe ID found
    }
}
// is only executed when ID not found
System.out.println("Student with ID " + studentID + " Was not found!)";