我试图在同一行上打印字符串和 int。但我得到一个错误。我知道解决这个错误的方法,但是为什么该行System.out.println("This is a string: %i", c2.a);给出错误而该行System.out.println("This is class method" + c2.a );给出正确的输出。下面是我的代码。
public class MyClass
{
private int a;
public double b;
public MyClass(int first, double second)
{
this.a = first;
this.b = second;
}
// new method
public static void incrementBoth(MyClass c1) {
c1.a = c1.a + 1;
c1.b = c1.b + 1.0;
}
//pass by valuye therefore no change
public static void incrementA(int a)
{
a = a+1;
}
public static void main(String[] args)
{
MyClass c1 = new MyClass(10, 20.5);
MyClass c2 = new MyClass(10, 31.5);
// different code below
incrementBoth(c2);
incrementA(c1.a);
System.out.println("This is a object passing: %i",c2.a);
System.out.println("This is object passing: " + c2.a );
System.out.println("This is pass by value: %d",c1.a);
}
}
Run Code Online (Sandbox Code Playgroud)
我的另一个问题是该行是否incrementBoth(c2)更改了 c2 的值,因为这里将整个对象传递给方法而不是按值传递incrementA(c1.a)
| 归档时间: |
|
| 查看次数: |
11150 次 |
| 最近记录: |