2016-02-07 252 views
0

我有3個選項在此代碼和我的其他類設置正確,據我所知。選項1和3似乎工作正常,但選項2我希望它打印聯繫人數量(它已經),打印每種聯繫人的數量,即個人或業務,然後打印所有聯繫人的平均年齡聯繫人。我無法弄清楚如何獲得平均年齡或如何打印每種類型。代碼與打印聯繫人列表,聯繫人數量,聯繫人數量,聯繫人的平均年齡和聯繫人的數量的選項集

進口java.util.Scanner的;

public class PlannerMain { static Sc​​anner scanner = new Scanner(System.in);

public static void main(String[] args) { 

    Contact[] contacts = new Contact[6]; 
    contacts[0] = new PersonalContact("Joe Smith, ", 33, ", 100 Evergreen Ave, ", "Seattle,", "WA ", 98999); // Personal 
    contacts[1] = new PersonalContact("Lawrence Williams, ", 45, ", 2000 1st St, ", "Tacoma,", "WA ", 98100); // Personal 
    contacts[2] = new PersonalContact("Rachel Garcia, ", 12, ", 12 Forest Drive, ", "Los Angelos,", "CA ", 99301); // Personal 
    contacts[3] = new BusinessContact("Gregory Smith, ", 67, ", 360-888-7777", " 360-555-6666"); // Business 
    contacts[4] = new BusinessContact("Jerome Bradley, ", 18, ", 216-111-2222", " 253-444-7777"); // Business 
    contacts[5] = new BusinessContact("Susie Adams, ", 23, ", 253-333-7777", " 425-666-9999"); // Business 

    while (true) { 

     System.out.println("1.Print planner contacts. "); 
     System.out.println("2.Print planner statistics. "); 
     System.out.println("3.Exit."); 

     int option = scanner.nextInt(); 

     if (option == 1) { // Displays every contact in the list until the length of the list has been reached 

      for (int i = 0; i < contacts.length; i++) { 
       System.out.println(contacts[i]); 

      } // End for 
     } // End option 1 

     else if (option == 2) { 
      int sum = 0; 
      System.out.println("Number of contacts: " + contacts.length); 

      for (int i = 0; i < contacts.length; i++){ 
       sum += contacts[i]; 
       } 
      System.out.println("Average age: " + (sum/contacts.length)); 

       if(contacts[] instanceof PersonalContact){    
       for (int i = 0; i < PersonalContact.getLength(); i++){ 
        System.out.println("Personal Contacts: " + personalContacts.length); 
       }// End for PC 
       }//End if PC 

       if(contacts[] instanceof BusinessContact){    
       for (int i = 0; i < BusinessContact.getLength(); i++){ 
        System.out.println("BusinessContacts: " + businessContacts.length); 
       }// End for BC 
       }//End if BC 

     } // End option 2 

     else if (option == 3) { /** Terminates the program */ 
      System.exit(0); 
     } // End option 3 
    } // End while 


}// End void main 

} //結束

回答

1

要獲得當前正在使用的和可變的,並試圖添加聯繫人[I],以它爲每一個接觸聯繫的平均年齡。你真正需要的是增加每個聯繫人來總和的年齡,使用類似

sum += contacts[i].getAge() 

sum += contacts[i].age 

取決於Contact類是如何實現的。

爲了讓你可以這樣做PersonalContacts和BusinessContacts數量:

int personalContactsCount = 0; 
for (int i = 0; i < contacts.length; i++) { 
    if (contacts[i] instanceof PersonalContact) { 
     personalContactsCount++; 
    } 
} 
int businessContactsCount = contacts.length - personalContactsCount;  
+0

感謝@Spencer是清除它適合我。看起來很簡單,哈哈 – Chap

相關問題