Flips测试类(page43)

本文探讨了Java类的应用,重点介绍了Counter类的功能及其在Flips类中的使用,通过实例展示了如何实现计数操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

测试用例:所用java类: StdOut,StdIn , Counter, StdRandom,

public class Flips {
    
    public static void main(String[] args) {
        
        int T = Integer.parseInt(args[0]);
        Counter heads = new Counter("heads");
        Counter tails = new Counter("tails");
        
        for (int t = 0; t < T; t++) 
            if(StdRandom.bernoulli(0.5))
                heads.increment();
            else tails.increment();
        StdOut.println(heads);
        StdOut.println(tails);
        int d = heads.tally() - tails.tally();
        StdOut.println("delta : " + Math.abs(d));
    }
}

打印结果:
public class Counter implements Comparable<Counter> { private final String name; // counter name private int count = 0; // current value /** * Initializes a new counter starting at 0, with the given id. * @param id the name of the counter */ public Counter(String id) { name = id; } /** * Increments the counter by 1. */ public void increment() { count++; } /** * Returns the current count. */ public int tally() { return count; } /** * Returns a string representation of this counter */ public String toString() { return count + " " + name; } /** * Compares this counter to that counter. */ public int compareTo(Counter that) { if (this.count < that.count) return -1; else if (this.count > that.count) return +1; else return 0; } }

public class Flips {
    
    public static void main(String[] args) {
        
        Counter c1 = new Counter("ones");
        c1.increment();
        Counter c2 = c1;
        c2.increment();
        StdOut.println(c1);
    }
}
//赋值语句的区别: 复制的是引用类型还是原始数据类型。

打印结果:

2 ones

 

转载于:https://www.cnblogs.com/pacoson/p/4003489.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值