Hoe de waarde van variabele in Java

en de fout is
De methode printf (string, object []) in het type Printstream is niet van toepassing op de argumenten (string, int)

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

werkt, maar wat als ik moet afdrukken

“De som van 5 en 6 is 11”

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

maar kreeg de bovenstaande fout over Eclipse Platformversie: 3.8.1 (Ubuntu)


Antwoord 1, Autoriteit 100%

Indien System.out.printfgeeft u deze foutmelding:

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

Dan moet u uw project configureren voor de juiste Java-versie.

Methoden met variabele argumenten werden geïntroduceerd met Java 5.

U kunt ook doen:

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

Antwoord 2, Autoriteit 67%

Bekijk deze vraag voor uw fout: Eclipse Java PrintF probleem Printstream is niet van toepassing

Als alternatief kunt u .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

Met de juiste Java-versieset werkt .printfook zoals verwacht

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

Antwoord 3, autoriteit 33%

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

Dit is een eenvoudige manier in de geformatteerde uitvoer

Other episodes