gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 08:23:02 26 4
gpt4 key购买 nike

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

必需:整数。发现:没有参数。原因:实际和形式参数列表的长度不同。

但是,我已将一个 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();


}

}

最佳答案

当您为类创建构造函数时,不会为该类创建任何默认构造函数。因此,如果您扩展该类并且子类试图调用其父类(super class)的无参数构造函数,则会出现编译时错误。

演示:

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];

关于java - 类中的构造函数不能应用于给定类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19788963/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com