2017-02-18 52 views
0

我试图在同一行上打印一个字符串和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)

+0

欢迎来到Stack Overflow!请参考[游览](http://stackoverflow.com/tour),环顾四周,阅读[帮助中心](http://stackoverflow.com/help),特别是[我该如何问一个好问题?](http://stackoverflow.com/help/how-to-ask)和[我可以问什么问题?](http://stackoverflow.com/help/on-topic)。 - 请一次只问一个问题。 –

+0

因为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。 –

+1

关于你的第二个问题,http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value?rq=1将是一个很好的阅读。 – fvu

回答

4

传递您需要使用printf方法,而不是println

println用于按原样打印原始类型,字符串和对象。另外,println只有一个参数作为输入。这就是当您在代码中传递多个参数时出现错误的原因。

printf另一方面用于格式化并将格式化的字符串打印到标准输出/错误。这是您在上面的代码中用于格式化输出的内容。

这是reference to the tutorials


希望这有助于!

+0

这给了我一个'在线程中的异常“main”java.util.UnknownFormatConversionException:Conversion ='i''。并没有给出输出。为什么? –

+0

https://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax – fvu

+0

您需要使用'%d'而不是'%i'。像这样:'System.out.println(“这是一个传递的对象:%d”,c2.a);' – anacron