我试图在同一行上打印一个字符串和int。但是我得到一个错误。我知道解决这个错误的方法,但为什么行System.out.println("This is a string: %i", c2.a);
给出了错误,而行System.out.println("This is class method" + c2.a);
给出了正确的输出。以下是我的代码。Java打印字符串和int在同一行上
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);
}
}
我的另一个问题是确实C2线incrementBoth(c2)
变化值,因为这里整个对象传递给方法,而不是通过值incrementA(c1.a)
欢迎来到Stack Overflow!请参考[游览](http://stackoverflow.com/tour),环顾四周,阅读[帮助中心](http://stackoverflow.com/help),特别是[我该如何问一个好问题?](http://stackoverflow.com/help/how-to-ask)和[我可以问什么问题?](http://stackoverflow.com/help/on-topic)。 - 请一次只问一个问题。 –
因为println()只接受一个参数,而不是两个参数。 https://docs.oracle.com/javase/8/docs/api/java/io/PrintStream.html#println-java.lang.String-。错误消息告诉你这一点。你应该阅读它。 printf()需要几个参数:https://docs.oracle.com/javase/8/docs/api/java/io/PrintStream.html#printf-java.lang.String-java.lang.Object...- 。所以,总之,阅读错误消息,并阅读javadoc。 –
关于你的第二个问题,http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value?rq=1将是一个很好的阅读。 – fvu