public class Duotai { public static void main(String [] args) { Count myCount = new Count(); Times Times=new Times(); for (int i=0;i<100;i++) increment(myCount,Times); System.out.println("count is "+myCount.count); System.out.println("time is "+Times.times); } public static void increment(Count c,Times times) { c.count++; times.times++; } } class Count{ public int count; public Count() { this.count = 1; } public Count(int count) { this.count = count; } } class Times{ public int times; public void setTimes() { this.times =1; } public void getTimes(int times) { this.times =times; }为什么times是100,而不是101
时间: 2023-07-15 09:12:02 浏览: 85
duotai.java
在主函数中,使用了一个循环语句,循环100次调用了increment方法。在每次调用increment方法时,都将Count对象c的count属性值加1,同时将Times对象times的times属性值加1。因此,最终Count对象c的count属性值为100,Times对象times的times属性值也为100,而不是101。如果想让Times对象的times属性值为101,可以将循环次数改为101,如下所示:
```
for (int i=0; i<101; i++) {
increment(myCount, Times);
}
```
这样就可以将Count对象的count属性值和Times对象的times属性值都加1到101了。
阅读全文