2010-10-26 48 views
1

我创建了一个为我做一些文件解析的类。我使得可以作为独立应用程序启动,从命令行获取文件名。 现在,我创建了另一个类,需要好好利用一下第一类是干什么的,我试图调用它像这样的主要方法:className.main(new String [] {“filename.txt”})?

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 
// [Ljava.lang.String;@63b9240e <--------------------------------------- 
//ROWCOUNT: 199 
//Exception in thread "main" java.lang.NullPointerException 

 

我是否需要再创建一个方法,做同样的事情,但有不同的名称?

谢谢

+3

Show yo你的代码,并解释你对'资源的引用'的含义。 – 2010-10-26 19:19:48

+1

并显示例外... – extraneon 2010-10-26 19:23:10

+0

如果我们有一些代码,我们可以看看它。但是你在那里应该有效。 – 2010-10-26 19:24:25

回答

0

您不应该为此目的使用main。重构您的旧类并创建一个名为parse(String path)的新方法。这种新方法应该尽一切努力使所有的工作。

public static void parse(String path) 

通过使公共其他类都可以访问它,静态意味着你不需要创建类的实例来使用它。你其他想要使用的第一类类会做

MyFirstClassName.parse("file.txt"); 
+0

是的,它似乎是唯一的东西。不过,我希望能以某种方式重新使用主要方法:(。谢谢。 – hummingBird 2010-10-26 19:31:20

0

我不明白。由于main是你的入口点,我不明白你是如何从外部方法调用它,如果它是程序启动时调用的第一个东西。只有在两个不同的类中声明了两个main方法,并且您从另一个类中调用另一个方法时才会起作用,注意最后一个是在应用程序启动时由JVM调用的方法。

在任何情况下,我建议你避免使用main作为泛型方法的名称,但它不是关键字,但我建议你只是将它重命名为其他名称。

+0

这就是我希望实现的目标:class2。主要调用class1.main。但是,由于class1.main期待命令行参数,因此我试图按照上面的描述来模仿它。对不起,我没有在第一时间发布代码片段。 – hummingBird 2010-10-26 19:28:58

3

我只是在回答有关打印字符串数组的一部分:

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

+0

谢谢你的seanizer。 – hummingBird 2010-10-26 19:41:06

相关问题