简体   繁体   English

Java在同一行上打印字符串和int

[英]Java print string and int on same line

I was trying to print a string and int on a same line. 我试图在同一行上打印字符串和整数。 But I get an error. 但是我得到一个错误。 I know my way around this error but why does the line System.out.println("This is a string: %i", c2.a); 我知道解决此错误的方法,但是为什么行System.out.println("This is a string: %i", c2.a); gives error whereas the line System.out.println("This is class method" + c2.a ); 给出错误,而行System.out.println("This is class method" + c2.a ); gives the correct output. 给出正确的输出。 Below is my code. 下面是我的代码。

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);
  }
}

My other question is does the line incrementBoth(c2) changes value of c2 because here whole object is passed to the method rather than passing by value in incrementA(c1.a) 我的另一个问题是,行incrementBoth(c2)更改incrementBoth(c2)值,因为这里整个对象都传递给该方法,而不是按incrementA(c1.a)值传递

You need to use the printf method and not println . 您需要使用printf方法而不是println

println is used to print primitive types, Strings and objects as they are. println用于按原样打印基本类型,字符串和对象。 Also, println takes only one argument as input. 另外,println仅接受一个参数作为输入。 That is the reason you are getting an error when you pass multiple arguments to it in your code. 这就是在代码中向其传递多个参数时收到错误的原因。

printf on the other hand is used to format and then print the formatted string to the Standard output / error. 另一方面, printf用于格式化,然后将格式化的字符串打印到标准输出/错误。 This is what you should use in your code above for formatting the output. 这就是您在上面的代码中用于格式化输出的内容。

Here's a reference to the tutorials . 这是教程参考


Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM