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
  •  | 
  •  

문제

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);
    }
}
도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top