Сканер ударил пустую строку, выбросить ArrayIndexOutOfBoundsException - PullRequest
0 голосов
/ 13 июля 2020

Сканер обнаруживает пустую строку throw ArrayIndexOutOfBoundsException Мой код генерирует исключение ArrayIndexOutOfBoundsException при попадании в пустую строку, как я могу это исправить? Например, строка 3 образца текстового файла является пустой строкой, которая вызовет исключение.

Сканер обнаружил пустую строку throw ArrayIndexOutOfBoundsException

Образец текстового файла

This is an 
Example

for this
Class

ABC
DEF

G

H



IIIIII


XYZ


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)); 
        
        }   
    } 
} 

Ответы [ 2 ]

1 голос
/ 13 июля 2020

Просто. Просто добавьте к строке проверку «isBlank».

  public static void main(String args[]) throws FileNotFoundException
  {
    Scanner file = new Scanner(new File("src/main/resources/Sample.txt"));

    while (file.hasNextLine()) {
      String input = file.nextLine();

      if(!input.isBlank()){
        String seq = input.toUpperCase().replaceAll("\\P{Alnum}", "");


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


    }
  }

, и результат будет примерно таким:

The length of the lps is 3
The length of the lps is 3
The length of the lps is 1
The length of the lps is 2
The length of the lps is 1
The length of the lps is 1
The length of the lps is 1
The length of the lps is 1
The length of the lps is 6
The length of the lps is 1
0 голосов
/ 13 июля 2020

Хотя решение @ Abhinaba действительно исправляет текущую ошибку, с которой вы сталкиваетесь, но оно не работает, когда входной файл содержит строки, содержащие только символы, отличные от букв и цифр c. Например:

This is an 
Example

for this
Class

ABC
DEF

G

H



IIIIII


XYZ    

#$%^

Вы можете изменить решение как:

    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}", "");

        if (!seq.isBlank()) {
            System.out.println("The length of the lps is "+ lps(seq));
        }

    }
}
...