Java 在同一行打印 string 和 int

Rah*_*nna 0 java

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

ana*_*ron 5

您需要使用该printf方法而不是println.

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

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

这是对教程参考


希望这可以帮助!