所以我正在做一项作业,我已经解决了所有问题,但作业的最后一部分是打印出通过 try-catch 从用户输入中导致执行错误的特定字符。例如,我输入“Greg Oxley”,问题应该是打印出“”作为错误原因。
我尝试使用Exception.getslacktrace、Exception.getcause()、Exception.getMessage()。最终仍然没有特定的字符。
System.out.print("Enter a single word (letters only, please): ");
String word = scan.nextLine();
//convert to all upper case
word = word.toUpperCase();
//count frequency of each letter in string
// Put the body of the first for loop in a try.
// Add a catch that catches the exception, but don’t do anything with it.
//Compile and run your program.
try{
for (int i=0; i < word.length(); i++)
counts[word.charAt(i)-'A']++;
}
catch (ArrayIndexOutOfBoundsException Exception)
{
System.out.println("Not a Letter: " + Exception.getMessage());
}
我应该获取导致异常“ArrayIndexOutOfBoundsException”的特定字符并将其打印出来。但相反,我仍然得到“ArrayIndexOutOfBoundsException”打印以及来自 Exception.getMessage() 的输出 - “索引 -12 超出长度 26 的范围”
最佳答案
在 try
语句之前声明 i
以便能够在 catch
语句中引用它:
int i = 0;
try{
for (; i < word.length(); i++)
counts[word.charAt(i)-'A']++;
}
catch (ArrayIndexOutOfBoundsException Exception)
{
System.out.println("Not a Letter: " + word.charAt(i));
}
如果你想在异常抛出后继续计数,你可以将 try/catch
语句移动到循环内,这样就不需要单独声明 i
了现在可以访问:
for (int i=0; i < word.length(); i++){
try{
counts[word.charAt(i)-'A']++;
}
catch (ArrayIndexOutOfBoundsException Exception){
System.out.println("Not a Letter: " + word.charAt(i));
}
}
关于java - 打印导致异常错误的特定字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57452115/