请给出下列程序的运行结果并给出原因 public class TestThis { int i = 0; TestThis increment() { i++; return this; } void print() { System.out.println("i = " + i); } public static void main(String[] args) { TestThis testThis = new TestThis(100); testThis.increment().increment().increment().print(); } } 输出结果: ; 原 因:
时间: 2023-06-27 16:04:21 浏览: 38
程序的运行结果应该是 "i = 3"。
原因是在程序中,首先创建了一个 TestThis 的实例 testThis,并将其初始化为 i=100。然后连续调用了三次 increment() 方法,并且每次调用都返回了 this(即当前对象),所以连续三次调用 increment() 方法等价于如下代码:
testThis.increment();
testThis.increment();
testThis.increment();
每次调用 increment() 方法都会将 i 的值加 1,并返回当前对象 this,所以最终 i 的值增加了 3。最后调用 print() 方法输出 i 的值,因此输出结果为 "i = 3"。
相关问题
public class TestThis { int i=0 ; TestThis increment() { i++; return this; } void a() { System.out.println("i = " + i); } public static void main(String[] args) { TestThis testThis = new TestThis(100
); testThis.increment().a(); //输出 i = 1
}
}
这段代码的输出结果是 i = 1。因为在 main 方法中,创建了一个 TestThis 对象 testThis,并调用了它的 increment 方法,该方法会将对象的 i 属性加一,并返回 this。由于返回的是 this,即当前对象,因此可以在调用 increment 方法的同时,调用 a 方法输出 i 的值,即 1。
public class Test{ public static void main(String[] args){ int times=0; while(int i=0;i<100;i++) increment(times); System.out.println(times); } public static void increment(int times) times++; }为什么times等于0
这段代码中,times初始值确实为0,但在调用increment方法时,传递给该方法的是times的副本,而不是原始的times变量。所以,increment方法中对副本的修改不会影响原始的times变量。因此,无论increment方法执行多少次,原始的times变量仍然保持为0,并且最终输出的结果也是0。如果要让程序输出100,可以将increment方法修改为返回修改后的值,并在main方法中接收返回值并更新times变量。