2012-11-23 58 views
0

我的一段代码将采用一个Patient对象,并通过一个存储患者对象的数组循环,如果匹配,它将在if语句中打印出所有消息好。但是如果病人不在那里,我相信每次病人不在候诊列表中时,其他部分都会打印出来。如果不在阵列中,我想要做的是让“您的患者不在等待列表中”打印一次?任何想法如何做到这一点?我试图想办法做到这一点,但我相信有一个简单的解决方案,我的大脑不能弄明白。用于在数组中循环打印一条语句java

public int findWaitingPosition (Patient patient) 
{ 
    for (int i=0 ; i <= waitingList.length-1 ; i++) 
    { 
     if (waitingList[i].equals(patient)) 
     { 
      System.out.println ("The patient is on waiting list: " + i+1); 
     } 
     else 
     { 
      System.out.println ("Your patient is not on the waiting list"); 
     } 

    } 
+1

如果您发现名称打印出来并退出该方法。将else子句移到for语句之外 –

+0

如果我这样做,即使它找到患者,它也会打印else子句,否?我将如何退出该方法? – Aaron

+0

如果发现患者并且您退出该方法,则else子句(移到for语句之外)将永远不会到达。所以不,它不会打印else子句,即使它找到了病人。 –

回答

2

我会用一个临时变量。此外,它看起来像你的方法应该返回阵列中的病人的位置。在这个片段-1意味着没有找到。

public int findWaitingPosition (Patient patient) 
{ 
    int position = -1; 
    for (int i=0 ; i <= waitingList.length-1 ; i++) 
    { 
     if (waitingList[i].equals(patient)) 
     { 
      position = i; 
      break; 
     } 
    } 
    if (position >= 0) 
     System.out.println ("The patient is on waiting list: " + i+1); 
    else 
     System.out.println ("Your patient is not on the waiting list"); 

    return position; 
} 
1

你可以改变你的循环如下:

boolean patientNotInList = true; 
for (int i=0 ; i <= waitingList.length-1 ; i++) 
{ 
    if (waitingList[i].equals(patient)) 
    { 
     System.out.println ("The patient is on waiting list: " + i+1); 
     patientNotInList = false; 
     break; //you might want to break the loop once the object is found 
    } 
} 
if(patientNotInList) { 
    System.out.println ("Your patient is not on the waiting list"); 
}