如何在java中打印变量的值

时间:2017-01-15 10:34:38

标签: java

System.out.printf("The sum is " + sum);

,错误是 PrintStream类型中的printf(String,Object [])方法不适用于参数(String,int)

System.out.printf("The sum of %d and %d  is %d . " ,a,b,sum);

工作但如果我需要打印

怎么办?
  

" 5和6的总和是11"

public boolean onNavigationItemSelected(MenuItem Item)
{
    int id = item.getItemId();

    if(id == R.id.activity2)
    {
        Intent goPage2 = new Intent(activity1.this, activity2.class);
        startActivity(goPage2);
    }
}

但是在Eclipse Platform Version:3.8.1(Ubuntu)上得到了上述错误

3 个答案:

答案 0 :(得分:4)

如果System.out.printf给你这个错误:

 The method printf(String, Object[]) in the type PrintStream is not applicable for the arguments (String, int)

然后,您必须为正确的Java版本配置项目。

Java 5引入了带有变量参数的方法。

或者,您可以这样做:

System.out.printf("The Sum of %d and %d is %d\n", new Object[] {a, b, sum});

答案 1 :(得分:3)

请针对您的错误查看此问题:Eclipse Java printf issue PrintStream is not applicable

或者,您可以使用.format

System.out.format("The sum of %d and %d  is %d . " ,1, 2, 3);

https://docs.oracle.com/javase/tutorial/java/data/numberformat.html

使用正确的Java版本集.printf也可以按预期工作

System.out.printf("The sum of %d and %d  is %d . " ,1, 2, 3);

答案 2 :(得分:2)

 int a = 2;
 int b = 4;
 int c = a + b;
 System.out.format("The sum of %d  and  %d is %d ", a, b, c);

这是格式化输出中的简单方法