有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java删除所有非大写字母字符,点击ArrayIndexOutOfBoundsException

扫描器命中空行抛出ArrayIndexOutOfBoundsException我的代码在命中空行时将抛出ArrayIndexOutOfBoundsException,我如何修复此问题?例如,示例文本文件的第3行是空行,将引发异常。 我想删除所有非大写字母字符。我该怎么做

示例文本文件

This is an 
Example

for this
Class

ABC
DEF

G

H



IIIIII


XYZ



!@#

(

Aaaabb

)


13


ABC

X

...//}{

--=+-


END
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.Scanner;

    class Test {
        // A utility function to get max of two integers 
        static int max(int x, int y) {
            return (x > y) ? x : y;
        }

        // Returns the length of the longest  
        // palindromic subsequence in seq 
        static int lps(String seq) {
            int n = seq.length();
            int i, j, cl;
            // Create a table to store results of subproblems 
            int L[][] = new int[n][n];

            // Strings of length 1 are palindrome of lentgh 1 
            for (i = 0; i < n; i++)
                L[i][i] = 1;

            // Build the table. Note that the lower  
            // diagonal values of table are 
            // useless and not filled in the process.  
            // The values are filled in a manner similar 
            //  to Matrix Chain Multiplication DP solution (See 
            // https://www.geeksforgeeks.org/matrix-chain-multiplication-dp-8/).  
            // cl is length of substring 
            for (cl = 2; cl <= n; cl++) {
                for (i = 0; i < n - cl + 1; i++) {
                    j = i + cl - 1;

                    if (seq.charAt(i) == seq.charAt(j) && cl == 2)
                        L[i][j] = 2;


                    if (seq.charAt(i) == seq.charAt(j))
                        L[i][j] = L[i + 1][j - 1] + 2;

                    else
                        L[i][j] = max(L[i][j - 1], L[i + 1][j]);
                }
            }

            return L[0][n - 1];
        }

        /* Driver program to test above functions */
        public static void main(String args[]) throws FileNotFoundException {
            Scanner file = new Scanner(new File("Sample.txt"));

            while (file.hasNextLine()) {
                String input = file.nextLine();
                String seq = input.toUpperCase().replaceAll("\\P{Alnum}", "");


                System.out.println("The length of the lps is " + lps(seq));

            }
        }
    }

共 (1) 个答案

  1. # 1 楼答案

    跳过空行

    添加条件if(n < 1) return 0;

    如果要从字符串中删除所有非大写字符,可以使用

    someString.replaceAll("[^A-Z]+", "");