2011-04-27 46 views
1

嗨, 我卡住了。我在代碼中遇到了2個問題,我在如何修復時遇到了一些問題。分配主要是無稽之談:Java - 構造函數的困境和System.out.print內的方法

import java.util.*; 

class Business { 
    private String name, phone; 
    private int employees, age; 

    void Business(){ 
     name = "Foo Inc."; 
     phone = ""; 
     employees = 0; 
     age = 0; 

     System.out.println("In default constructor!"); 
     printVals(); 
    } 

    void Business(String name, String phone, int employees){ 
     System.out.printf("%s %s %d\n", name, phone, employees); 

     this.name = name; 
     this.phone = phone; 
     this.employees = employees; 
     this.age = 0; 

     System.out.println("In constructor!"); 
     printVals(); 
    } 

    void printVals(){ 
     System.out.printf("name: %s\n", name); 
     System.out.printf("phone: %s\n", phone); 
     System.out.printf("employees: %d\n", employees); 
     System.out.printf("age: %d\n", age); 
    } 

    public static void main(String [] args) 
    { 
     Business[] mall = new Business[5]; 
     String[] names = {"The Gap", 
          "Savers", 
          "Academy of Salon Professionals", 
          "Ron's Farmhouse"}; 
     String[] phones = {"555-555-5555", "555-555-5556", 
          "555-555-5557", "555-555-5558"}; 
     int[] emps = {20, 24, 75, 32}; 
     int i, num = 4; 


     mall[num - 1] = new Business(); 
     for(i = 0; i < num; i++){ 
      mall[i] = new Business(names[i], phones[i], emps[i]); 
      System.out.printf("init Business: %s %s %d\n", 
        names[i], phones[i], emps[i]); 
     } 
    } 
} 

這裏從javac的是輸出錯誤:

Business.java:51: cannot find symbol 
symbol : constructor Business(java.lang.String,java.lang.String,int) 
location: class Business 
      mall[i] = new Business(names[i], phones[i], emps[i]); 
        ^
1 error 

我不明白爲什麼這是告訴我它無法找到構造函數。據我所知,參數是相同的...

比方說,我註釋掉Business()調用的參數,使它只調用默認的構造函數。至少它編譯的方式是這樣的,但是在方法中沒有任何System.out.print *會打印任何東西!

任何幫助,將不勝感激。

回答

6

您正在使用void Business定義構造函數。構造函數沒有返回類型,因此只需在商業「構造函數」和new能夠找到它們之前刪除該void。

/* remove void */ 
Business(String name, String phone, int employees){ 
    System.out.printf("%s %s %d\n", name, phone, employees); 

    this.name = name; 
    this.phone = phone; 
    this.employees = employees; 
    this.age = 0; 

    System.out.println("In constructor!"); 
    printVals(); 
} 
+0

出色的發揮。 – edwardsmatt 2011-04-27 01:40:39

0

從構造函數實際上描述的「爲什麼」無效不應該在構造函數刪除void