gpt4 book ai didi

java - 在Eclipse中正确的try-catch输出,但在cmd中不正确

转载 作者:行者123 更新时间:2023-12-03 08:55:27 25 4
gpt4 key购买 nike

我为此自欺欺人。
我试图捕获调用我编写的Java程序时从命令行输入的参数数量,在Eclipse中我得到了正确的输出,但是在win cmd中我得到了ArrayIndexOutOfBoundException。
然后我再次使用try-catch,它可以在eclipse中运行,但不能在win cmd中运行...我还缺少什么?

如果我插入所有参数都可以从两端完美地工作,那只是当我想获取缺少的参数时,它是行不通的。

下面是我使用的代码的简化版本:

public static PrintWriter outWrite;
public static String[] allInput;

public static void main(String [] args) {

// I first tried this

if(args.length==0){
System.out.println("Missing arguments. Please try again");
System.exit(0);
}
if (args.length==1){
System.out.println("Missing second argument. Please try again");
System.exit(0);
}


// and then the try-catch, I leave both of them here so you can see them

try{
myMethod(args[0]);
String input2 = args[1];
// here I'm just saving the output of myMethod to the input2
try {
outWrite = new PrintWriter(input2, "UTF-8");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

} catch (ArrayIndexOutOfBoundsException e){
System.out.println("Missing arguments. Please try again");
System.exit(0);
}
}

我也看着这个 Eclipse gives different output than cmd using runtime exec没有成功

--- EDIT添加命令行使用和精确错误:----
win中使用的命令行是 java Driver,它应该向我发送我在代码中编写的消息
相反,它给了我以下内容:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at myPackage.Driver.main(Driver.java:31)

错误中的 line 31对应于以上代码段 main()方法内的第一行。

在 eclipse 中 (Driver.java:31)的另一个数字正确指向 myMethod(args[0])

正确的命令行是 java myPackage.Driver fileIn.txt fileOut.txt,它在win cmd和eclipse中都可以正常使用

任何帮助都是极好的!
谢谢 :)

最佳答案

好了,经过两天的尝试和头痛,我找到了解决方案:

该错误是由于Eclipse编译.java文件而您需要在Win或Mac中使用javac进行处理而导致的。

我无法在Win中使用javac,因为它给了我javac is not recognized error(我刚刚更换了PC),在这里查找javac is not recognized as an internal or external command, operable program or batch file后,我可以使用以下命令对其进行编译:
我的javac *.java文件夹中的src
从那里,我终于能够从两侧(cmd和eclipse)获得正确的错误处理消息

我承认我不完全确定为什么只要我使用了两个参数就可以从cmd获取正确的输出,但是上述解决方案对我有用。

关于java - 在Eclipse中正确的try-catch输出,但在cmd中不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27277851/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com