Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print the value of variable in java [duplicate]

Tags:

java

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)

like image 415
Sagar Devkota Avatar asked Sep 05 '25 16:09

Sagar Devkota


2 Answers

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});
like image 125
john16384 Avatar answered Sep 07 '25 08:09

john16384


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);
like image 29
ppasler Avatar answered Sep 07 '25 08:09

ppasler