![](/img/trans.png)
[英]i keep getting an error when I try to call a method into my main function
[英]I'm unsure what to put in my try statement and I keep getting an “Ecxeption in thread ”main“” error
每當我嘗試運行我的代碼時,它都會在第一個打印語句中到達第兩個打印語句,然后在線程“ main”中給我一個異常。java.lang.ArrayIndexOutOfBoundsException:模板處索引0超出長度0的范圍。 :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();
}
}
}
如果出現問題,我將包括第二類文件。 我們應該掃描另一個類中的文件,並將其放入此類中的字符串中。 我們上一個程序沒有多個班級,上課很簡短,我很迷茫和困惑。
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
第1課:您不要嘗試/捕捉您不了解 (期望會發生)的異常! 此類異常是代碼中的錯誤 ,您可以對其進行調試並修復根本原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.