今天,我弟遇到一個有意思的錯誤~
程序:
package com.mq.ceshi1;
public class StringFormat {
public static void main(String[] args) {
int num = 10;
int num2 = 5;
System.out.println(String.format("%d / %d = %d", num,num2,num / num2));
}
}
報了The method format(String, Object[]) in the type String is not applicable for the arguments (String, int,int,int)錯誤。
首先分析一下,jdk文檔:

可見,這個是在1.5版本后添加的。
后來,根據網上的修改,按以下運行也是正常的。
package com.mq.ceshi1;
public class StringFormat {
public static void main(String[] args) {
// int num = 10;
// int num2 = 5;
Integer [] nums = {10,5,2};
// System.out.println(String.format("%d / %d = %d", num,num2,num / num2));
System.out.println(String.format("%d / %d = %d", nums));
}
}
查看了出問題機器使用的是:jdk版本也是1.7.8 myecliplse8.6
由於版本大於1.5,但是我還是懷疑是版本引起的。於是,在有問題的機器上,由使用了1.5版本之后才有的自動拆裝箱機制。
Integer num = 5; //發現報錯
進一步驗證了我關於版本可能帶來的錯誤。
於是,將myecliplse版本升級到2014版,發現問題消失。
總結:懷疑是myeclipse8.6版本與jdk1.7.8存在不兼容的問題。(暫無直接證據,如果哪位有方法驗證的話,請不吝賜教!!)
