我创建了一个为我做一些文件解析的类。我使作为独立应用程序启动成为可能,从命令行获取文件名。 现在我创建了另一个类,它需要利用第一个类正在做的事情,我试着像这样调用它的主要方法:
className.main(new String[]{"filename.txt"});
但是,事情似乎不太顺利,因为我遇到了一些空指针异常。当我插入 system.out.println(args[0])
为了查看发生了什么,我得到了对资源的引用,而不是我期望的字符串。
这里是更多的代码:
// this is from the class that is reffered as 'new one'
// Cal the maze solver now for out.txt
String[] outFile = new String[]{"out.txt"};
MazeSolver.main(outFile);
// this is part of the MazeSolver main method
public static void main(String[] args) {
if(args.length != 1) {
System.out.println("Usage: java MazeSolver ");
System.exit(0);
}
// this is the part where i tried to debug
System.out.println(args.toString());
// and this is the error message that i got in terminal
// <b>[Ljava.lang.String;@63b9240e</b> <---------------------------------------
//ROWCOUNT: 199
//Exception in thread "main" java.lang.NullPointerException
我是否需要再创建一个方法,做完全相同的事情,但名称不同?
谢谢
最佳答案
我只是在回答有关打印字符串数组的部分:
System.out.println(args.toString());
这行不通,Array.toString() 只是返回一个内部表示。您将需要使用辅助方法 Arrays.toString(arr)
在 Arrays
类中:
System.out.println(Arrays.toString(args));
或者,如果您要处理多维数组,请使用 Arrays.deepToString(arr)
:
final Object[][] arr = new Object[3][];
arr[0]=new String[]{"a","b","c"};
arr[1]=new Integer[]{1,2,3,4,5};
arr[2]=new Boolean[]{true,false};
System.out.println(Arrays.deepToString(arr));
输出:
[[a, b, c], [1, 2, 3, 4, 5], [true, false]]
关于java - className.main(new String[] {"filename.txt"})?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4027178/