我試圖在同一行上打印一個字符串和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