gpt4 book ai didi

java - 错误调用方法

转载 作者:行者123 更新时间:2023-11-29 05:00:10 26 4
gpt4 key购买 nike

我正在做一项类作业,要求抛硬币并记录它正面朝上或反面朝上的次数。我很确定其中大部分是正确的,但让我失望的部分是调用方法“coinFlip”。当我尝试在计数器类中调用它时,我收到错误消息“coinFlip 无法解析为类型”我似乎无法弄清楚如何修复它,或者理解为什么我会收到该消息.感谢任何帮助,提前致谢。

package coinProject;

public class GenericCoin {

public class coinFlip{
private int heads = 0;
private int sideUp; //used to record which side the coin lands on

public coinFlip(){
flip();
}

public void flip(){
sideUp = (int) (Math.random() * 2);//used to keep random number under 2
}

public boolean headFlip(){
return (sideUp == heads);
}

public String toString(){//limits to only two print options, heads or tails
return (sideUp == heads) ? "Heads" : "Tails";
}
}

}

============================================= =================================

package coinProject;



public class counter {

public static void main(String[] args){

final int flip = 50;
int headFlips = 0 , tailFlips = 0;

coinFlip coin = new coinFlip();


for(int i = 1; i <= flip; i++){
coin.flip();

if(coin.headFlip()){
headFlips ++;
}
else{
tailFlips ++;
}

System.out.println(coin.toString());
}

System.out.println();//creates gaps after flips
System.out.println();

System.out.println("----- Flipped: " + flip);
System.out.println("----- Heads: " + headFlips);
System.out.println("----- Tails: " + tailFlips);


}

}

最佳答案

您已将 coinFlip 定义为内部类,因此在实例化 `coinFlip' 之前需要一个 GenericCoin 的实例。所以你需要:

GenericCoin.coinFlip coin = new GenericCoin().new coinFlip();

关于java - 错误调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32366989/

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