每当我尝试运行我的代码时,它都会先到达前两个打印语句,然后再给我一个 线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException:索引 0 超出长度 0 的范围 在 templates.SentenceUtilsTest.main(SentenceUtilsTest.java:26)
我很迷茫,我的教授没有解释 try-catch 语句,这与我们之前的作业相比难度有很大的提高。
包中还有另一个类。
package templates;
public class SentenceUtilsTest
{
private static List<SentenceUtils> sList = new ArrayList<SentenceUtils>();
public static void main(String[] args)
{
System.out.println("\n---------------------------------------------------\n");
System.out.println("COP3330 Sentence Utility Program by [name]");
System.out.println("\nInput file name: " + args[ 0 ] );
try
{
File file = new File("cat.txt");
Scanner scanner = new Scanner(file);
//insert code
scanner.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
}
我包含了第二类文件,以防出现问题。我们应该从另一个类中扫描文件,并将其放入此类中的字符串中。我们上一个项目没有多个类(class),并且在类里面进行了非常简短的介绍,我感到非常迷失和困惑。
public class SentenceUtils
{
private String sentence;
private String[] tokens;
private String[] shingles;
public SentenceUtils( String s )
{
sentence = s;
generateTokens();
generateShingles();
}
private void generateTokens()
{
//code
}
private void generateShingles()
{
//code
}
public void report()
{
//code
}
}
输出为
---------------------------------------------------
COP3330 Sentence Utility Program by [name]
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index
0 out of bounds for length 0
at templates.SentenceUtilsTest.main(SentenceUtilsTest.java:26)
预期输出是
---------------------------------------------------
COP3330 Sentence Utility Program by [name]
Input file name: [file name]
Number of sentences: [number]
Sentence 0 >
//The next parts are from the second class, specifically report()
The cat in the hat
Tokens:
0:The
1:cat
2:in
3:the
4:hat
Shingles:
//I have the logic for this laid out in my program, didn't think it
//necessary to copy and paste though
最佳答案
这里:
System.out.println("\nInput file name: " + args[ 0 ] );
您正在无条件打印 args[0]。
堆栈跟踪告诉您无法打印长度为 0 的数组的第一个索引 (0)。就是这么简单:空数组没有任何索引。 args
包含调用类时传递给 JVM 的参数。所以除非你向它传递值,否则它是完全空的!
因此,您要么应该至少向应用程序传递一个值,要么需要某种检查,例如
if (args.length < whateverValueYouExcpect) {
give error message
第一课:不要尝试/捕获您不理解(预计会发生)的异常!此类异常是代码中的错误,您可以对其进行调试,并修复根本原因。
关于java - 我不确定在 try 语句中添加什么内容,并且不断收到 "Ecxeption in thread "main""错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54620132/