类中的构造函数不能应用于给定的类型

时间:2013-11-05 12:25:27

标签: java

我使用数组得到以下代码来查找一些原始数字。但是,在尝试编译我的用户类PalindromeArrayUser时,它说 - “类中的构造函数不能应用于给定的类型”

必需:int。 发现:没有争论。 原因:实际和正式的参数列表长度不同。

但是,我已经将构造函数传递给了一个int值(与我的蓝图中设计的方式相同)。我不太明白问题的来源。谢谢。

这是我的两个班级

 public class PalindromeArray 
 {

int arrLength;

public PalindromeArray(int InputValue) 
{
    arrLength = InputValue;
}


int arr[] = new int[arrLength];
boolean check[] = new boolean [arrLength];


public void InitializeArray()  
{

    for (int k = 2; k < arr.length; k++)
    {
        arr[k] = k;
        check[k] = true;

    }   
}

public void primeCheck()  
{

    for (int i = 2; i < Math.sqrt(arr.length - 1); i++ )
    {
        if (check[i] == true)
        {
        for (int j = 2; j < arr.length; j++)
          {
            if (j % i == 0)
                {
                     check[j] = false;
                     check[i] = true;
                }
          }
        }   

    }   
}

public void PrintArray() 
{
    for (int k = 2; k < arr.length; k++)
    {
        if ((!check[k]) == false)
            System.out.println(arr[k]);

    }
}

   }

这是我的用户类,问题来自于此。上面的类编译得很好。

 import java.io.*;

 public class PalindromeArrayUser extends PalindromeArray
 {
public static void main(String argv[]) throws IOException 
{
    BufferedReader input = new BufferedReader(new InputStreamReader(System.in));

    System.out.println("Please enter the upper bound.");

    String line = input.readLine();

    int InputUser = Integer.parseInt(line);
                                     // this is where I pass the same int type as I  
                                                  // constructed it
    PalindromeArray palindrome = new PalindromeArray(InputUser);
    palindrome.InitializeArray();
    palindrome.primeCheck();
    palindrome.PrintArray();


}

 }

3 个答案:

答案 0 :(得分:7)

为类创建构造函数时,不会为该类创建任何默认构造函数。因此,如果你扩展该类,并且如果子类试图调用其超类的no-arg构造函数,则会出现编译时错误。

演示:

class Parent {
  int i;
  public Parent(int i) {
    this.i=i;
  }
}

class Child extends Parent {
  int j;
  public Child(int i, int j) {
    super(i);
    this.j=j;
  }
  public Child(int j) {
    // here a call to super() is made, but since there is no no-arg constructor
    // for class Parent there will be a compile time error
    this.j=j;
  }
}

修改

要回答您的问题,请不要将值arrLength分配给arr[]check[],因为当时arrLength为0

所以就像这样声明他们

int arr[];
boolean check[];

并在将输入分配给arrLength之后的构造函数中放置这些语句。

arr = new int[arrLength];
check = new boolean [arrLength];

答案 1 :(得分:3)

错误是因为您延长了PalindromeArray。这不是必需的。 子类(您的PalindromeArrayUser)必须为构造函数提供一个int。

如果您的超类没有默认构造函数,那么在子类构造函数中必须从超类调用非默认构造函数之一。 (super(params)

答案 2 :(得分:2)

错误是因为您正在扩展PalindromeArray,它具有显式构造函数。您必须为构造函数提供参数。

  

因为B中没有可用的默认构造函数,因为编译器错误消息指示。在类中定义构造函数后,不包含默认构造函数。如果您定义任何构造函数,那么您必须定义所有构造函数。

了解更多here

免责声明:以上摘自文章