首先 - 要明确 - 这个是作业,我只是想学会正确地做这件事(我不想要答案,只是指导) 。我在这个网站上做了一些搜索,但谷歌一直在寻找解决方案。
反正:
在我的主要课程中,我创建了一个我试图传递给方法的ArrayList。由于某种原因,我无法传递ArrayList作为参数,即使该方法设置为接收一个。我遇到错误:"类中的构造函数不能应用于给定的类型。"
可能我犯了一个简单的错误 - 任何人都可以帮助我理解这里发生了什么吗?
public static void main(String[] args)
{
Deck cards = new Deck();
ArrayList<String> deck = new ArrayList();
deck = cards.CreateDeck();
Hand myHand = new Hand(deck); //here is the error
}
...然后
public class Hand {
public static ArrayList<String> Hand (ArrayList<String> deck)
{
ArrayList<String> yourHand = new ArrayList<String>(deck);
for (int i = 5; i < yourHand.size(); i++) {
yourHand.remove(i);
}
return yourHand;
}
}
答案 0 :(得分:0)
您尝试在try {
final String[] fields = stat.substring(stat.lastIndexOf(field2End)).split(fieldSep);
final long t = Long.parseLong(fields[fieldStartTime]);
final int tckName = Class.forName("libcore.io.OsConstants").getField("_SC_CLK_TCK").getInt(null);
final Object os = Class.forName("libcore.io.Libcore").getField("os").get(null);
final long tck = (Long)os.getClass().getMethod("sysconf", Integer.TYPE).invoke(os, tckName);
return t * msInSec / tck;
} catch (final NumberFormatException e) {
throw new IOException(e);
} catch (final IndexOutOfBoundsException e) {
throw new IOException(e);
} catch (java.lang.ClassNotfoundException e) {
throw new IOException(e);
} catch (java.lang.NoSuchMethodException e) {
throw new IOException(e);
} catch (IllegalAccessException e) {
throw new IOException(e);
}
类构造函数中传递Arraylist
,但没有构造函数接受Hand
类中的列表。
您需要在Hand
类
Hand
答案 1 :(得分:0)
您正在尝试使用静态方法实例化Hand,但这不起作用。
如果您的意图是将ArrayList
传递给Hand
内的方法,请执行以下操作:
将方法的名称更改为其他名称(不以大写字母开头),并删除new
中的main
关键字。
public static void main(String[] args)
{
Deck cards = new Deck();
ArrayList<String> deck = new ArrayList();
deck = cards.CreateDeck();
//You had Hand as a method, which can't be initialized!
List<String> changedDeck = doSomethingWithDeck(deck);
}
然后,使用静态方法的类看起来像:
public class Hand {
public static ArrayList<String> doSomethingWithDeck(ArrayList<String> deck)
{
ArrayList<String> yourHand = new ArrayList<String>(deck);
for (int i = 5; i < yourHand.size(); i++) {
yourHand.remove(i);
}
return yourHand;
}
}
但是,如果你的意图是实际创建一只手,你需要解释你的意图是什么,因为构造函数不能是静态的,也不能返回值。
答案 2 :(得分:0)
构造函数不能有返回类型,它们也不能是static
。
您实际定义的是一个类方法,可以在不实例化Hand
对象的情况下调用它。调用Hand.Hand(deck)
将返回ArrayList<String>
,而不是Hand
对象。此外,该方法不应与该类具有相同的名称。