以下是代碼。If/else沒有被正確處理? (Java)
import java.lang.reflect.*;
class Invoke {
public static void main(String[] args) {
int ret;
if (args.length<2) {
System.out.println("Usage: Invoke <class> <method>");
return;
}
if (args.length == 2) {
ret = 2
} else {
System.out.println("Additional parameters not yet supported.");
return;
}
System.out.println("Results: " + ret);
}
}
的問題是,即使我運行程序與類似...
java -cp Invoke;HelloJava4 Invoke HelloJava4 param1 param2 param3
...它仍然承認「參數1參數2參數3」作爲一個參數。注:我的系統的類路徑設置爲C:\JavaSource
,所以-cp Invoke;HelloJava4
使得搜索Invoke.class和HelloJava4.class
如果我做System.out.println(args.length);
,它將輸出給定參數的正確數目,但是當我請使用以下if
語句進行檢查,它將運行if
代碼塊,而不是else
代碼塊。
if (args.length == 2) {
ret = 2
} else {
System.out.println("Additional parameters not supported yet.");
return;
}
是什麼給出的? :困惑:
這裏是未經編輯的代碼,在全:
import java.lang.reflect.*;
class Invoke {
public static void main(String[] args) {
Object ret;
for (String arg : args)
System.out.println(arg);
System.out.println("Count: " + args.length + " \n");
if (args.length<2) {
System.out.println("Usage: Invoke <class> <method>");
return;
}
try {
Class theClass = Class.forName(args[0]);
Method theMethod = theClass.getMethod(args[1]);
if (args.length == 2) {
System.out.println("Invoking method " + args[1] + " within class " + args[0]);
ret = theMethod.invoke(null);
} else {
// pass parameters to .invoke() if more than two args are given
// for now, just exit...
System.out.println("Parameter passing not yet supported.");
return;
}
System.out.println("Invoked static method: " + args[1]
+ " of class: " + args[0]
+ " with no args\nResults: " + ret);
} catch (ClassNotFoundException e) {
System.out.println("Class (" + args[0] + ") not found.");
} catch (NoSuchMethodException e2) {
System.out.println("Class (" + args[0] + ") found, but method does not exist.");
} catch (IllegalAccessException e3) {
System.out.println("Class (" + args[0] + ") and method found, but method is not accessible.");
} catch (InvocationTargetException e4) {
System.out.println("Method threw exception: " + e4.getTargetException());
}
}
}
這裏是精確的輸出它提供:
C:\JavaSource>cd invoke
C:\JavaSource>javac invoke.java
Note: invoke.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
C:\JavaSource>cd ..
C:\JavaSource>java -cp Invoke;HelloJava4 Invoke HelloJava4 param1 param2 p
aram3
HelloJava4
param1
param2
param3
Count: 4
Class (HelloJava4) found, but method does not exist.
說真的。 Java是錯誤的?我想你會發現Java處理事情就好了,包括塊。當你認爲它沒有這樣做時,仔細查看* your *代碼中的錯誤,或者*瞭解Java是如何工作的。 –
我不確定我相信你;我不能欺騙這個。你確定你重新編譯了/ etc? –
您是否嘗試過打印參數的內容? –