如何在for循环中添加try-catch块来捕获arrayindexoutofbounds异常?

trnvg8h3  于 2021-07-06  发布在  Java
关注(0)|答案(2)|浏览(322)

我是新来使用试抓块,我需要一些方向。我有一个程序,计算从用户输入的一个短语中输入的字母。字母“a”到“z”通过从“z”的值减去正在处理的字母的unicode字符集索引值的相应值(即90),转换为0到25之间的数字。如何在第一个for循环中添加try-catch块,将字符转换为索引,以便如果短语包含任何非字母的字符,它将在arrayindexoutofboundsexception中捕获它。然后我会有一条消息,在一条语句中打印出非字母字符给用户。我知道我想做什么,但是,我有一点困难,理解语法,我需要这样做。我尝试添加if(counts[i]<=64 | |>=91),但似乎不起作用。我需要把它转换成字符串吗?我知道我的代码应该是这样的:

try {
     code...
 }
 catch (StringIndexOutOfBoundsException exception)
 {
    System.out.println("Not a letter: " + counts);
 }

Here is my code without the try/catch block:

import java.util.Scanner;
public class CountLetters
{
 public static void main(String[] args)
 {
 int[] counts = new int[26];
 Scanner scan = new Scanner(System.in);
 //get word from user
 System.out.print("\n Enter a single word (letters only): ");
 String word = scan.nextLine();
 scan.close();

 //convert to all upper case
 word = word.toUpperCase();

 //count frequency of each letter in string
  for (int i=0; i < word.length(); i++)
 counts[word.charAt(i)-'A']++;

 //print frequencies
 System.out.println();
 for (int i=0; i < counts.length; i++)
 if (counts [i] != 0)
 System.out.println((char)(i +'A') + ": " + counts[i]);
 }
}
b4qexyjb

b4qexyjb1#

你要做的就是 counts[word.charAt(i) - 'A']++ 内部 try-catch 块,如下所示:

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        int[] counts = new int[26];
        Scanner scan = new Scanner(System.in);
        // Get word from user
        System.out.print("Enter a single word (letters only): ");
        String word = scan.nextLine();
        scan.close();// Do not close it.

        // Convert to all upper case
        word = word.toUpperCase();

        // Count frequency of each letter in string
        for (int i = 0; i < word.length(); i++) {
            char ch = word.charAt(i);
            try {
                counts[ch - 'A']++;// Check this for exception
            } catch (ArrayIndexOutOfBoundsException e) {
                System.out.println("'" + ch + "' is non-alphabetic character.");
            }
        }

        // Print frequencies
        System.out.println();
        for (int i = 0; i < counts.length; i++) {
            if (counts[i] != 0) {
                System.out.println((char) (i + 'A') + ": " + counts[i]);
            }
        }
    }
}

示例运行:

Enter a single word (letters only): hello2world
'2' is non-alphabetic character.

D: 1
E: 1
H: 1
L: 3
O: 2
R: 1
W: 1

一些建议:
请勿关闭 Scanner(System.in) 因为它也关闭了 System.in 再也没有办法打开它了。
使用 {} 对于循环块或 if/else/else if 即使只有一句话。

r55awzrz

r55awzrz2#

与其捕获异常,不如检查循环:

for (int i=0; i < word.length(); i++) {
            char currentChar = word.charAt(i);
            if (currentChar >= 'A' && currentChar <= 'Z') {
                counts[currentChar -'A']++;
            }
        }

正如在注解中提到的,您的代码不应该依赖于捕获越界异常。

相关问题