4
System.out.printf("The Sum is %d%n" , sum);

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

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

Works but What if i need to print

"The Sum of 5 and 6 is 11"

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

But got the above error on Eclipse Platform Version: 3.8.1 (Ubuntu)

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
Sagar Devkota
  • 1,295
  • 3
  • 12
  • 25
  • 1
    The Error in `System.out.printf("The Sum is %d%n" , sum);` is the %n, You surely meant \n. – Turo Jan 15 '17 at 10:39
  • Exception in thread "main" java.lang.Error: Unresolved compilation problem: The method printf(String, Object[]) in the type PrintStream is not applicable for the arguments (String, int) at addition.main(addition.java:25) Is the error. – Sagar Devkota Jan 15 '17 at 10:51
  • @Turo `%n` is valid. – Tom Jan 15 '17 at 10:55

3 Answers3

7

If System.out.printf is giving you this error:

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

Then you must configure your project for the proper Java version.

Methods with variable arguments were introduced with Java 5.

Alternatively, you could do:

System.out.printf("The Sum of %d and %d is %d\n", new Object[] {a, b, sum});
john16384
  • 7,800
  • 2
  • 30
  • 44
4

Have look at this question for your error: Eclipse Java printf issue PrintStream is not applicable

Alternatively you can use .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

With proper Java version set .printf also works as expected

System.out.printf("The sum of %d and %d  is %d . " ,1, 2, 3);
Jorrick Sleijster
  • 935
  • 1
  • 9
  • 22
ppasler
  • 3,579
  • 5
  • 31
  • 51
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);

This is simple way in the formatted output