调用方法

时间:2015-09-03 04:31:57

标签: java methods error-handling

我正在进行课堂作业,让硬币翻转并记录它落在头上或尾巴上的次数。我很确定大部分是正确的但是让我失望的部分是调用方法“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);


    }

}

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

阅读Oracle tutorial on nested classes:您需要将coinFlip类定义为public static class coinFlip而不是public class coinFlip,后者需要封闭类的实例,如@ user2341963所述