I need to make this code work, but cannot figure out what is wrong. It is a System.out.format() issue

StackOverflow https://stackoverflow.com/questions/23123134

  •  05-07-2023
  •  | 
  •  

Question

I cannot seem to get this code to format. I keep getting this error:

Exception in thread 
    "main" java.lang.Error: Unresolved compilation problem: 
    The method format(String, Object[]) in the type PrintStream is not applicable 
    for the arguments (String, int, double) at 
    org.lineware.learningjava.Root2.main(Root2.java:9)

Here is the code:

public class Root2 {

    public static void main(String[] args) {
        int i = 2;
        double r =  Math.sqrt(i);
        System.out.format("The square root of %d is %f.%n", i, r);
    }
}
Was it helpful?

Solution

Variable arguments (varargs) were added in Java 5. Before that the format(..) method you were trying to use was declared as

public PrintStream format(String format, Object[] args) {

In other words, it expected an array of objects. Since Java 5, the method is declared as

public PrintStream format(String format, Object... args) {

using the varargs syntax. You're probably using a compiler version lower than Java 5.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top