NullPointerException от копирования растущего внутреннего массива и внешнего массива - PullRequest
0 голосов
/ 20 декабря 2018

Я провел как можно больше исследований по подобным вопросам о 2D-массивах и NullPointerException (NPE), но не нашел ответа, который напоминал бы мою ситуацию.

Моя программа должна быть оченьbasic: взять входной файл "image" с целочисленными значениями и "смягчить" эти значения, взяв среднее значение вокруг каждого.

У меня возникли проблемы с начальным процессом копирования файла в2-мерный массив с циклами while, хотя циклы, похоже, не являются проблемой, поскольку я уже пробовал цикл do - while.

Сначала я пытался использовать Arrays.copyOf для копирования массивов., но это изначально дало мне NPE, поэтому я попытался написать свои собственные статические методы, чтобы выполнить эту работу, потому что я где-то читал, что Arrays.copyOf работает только для одномерных массивов.

public class ex7_imageSmoother {
    public static void main ( String[] args ) throws IOException {

//  build utility object(s)
    Scanner ScUser = new Scanner( System.in );

//  ph for ascii art
    System.out.println( "\n\nAre your ready to Soften some \"hard\" files?" );

  ////..repeat program by prompt
        String stRepeat1;
        do {

    //  get hard file name to be softened
        System.out.print( "\n\nWhat file would you like to soften? " );

        String  StHardName = ScUser.nextLine().trim();
        File    FiHardIn   = new File   ( StHardName );
        Scanner ScHardIn   = new Scanner( FiHardIn );

  //--  build 2d "Hard" array
    //  array will be of at least one cell
        int[][] AyHardImg = { { 0 } } ;  

        int iRowCount = 0;

  ////  for every line in the file; i.e. check that there is a next line
        while (ScHardIn.hasNextLine() ) {

        //  create a string that can be read through by scanner for every line of the file
            String StInLine = ScHardIn.nextLine();
        //  build scanner to read through each row
            Scanner ScInLine = new Scanner( StInLine );

        //  use static method to copy array; make larger on further iterations
            AyHardImg = smCopyArrayOuter( AyHardImg, iRowCount );

            int iColCount = 0;

      ////  for every integer in the row
            while ( ScInLine.hasNextInt() ) {

            //  create temporary array in an attempt to circumvent NPE
                int[] temp = new int[ AyHardImg[ iRowCount ].length ]; // ...--... this line creates the NPE!!

            //  copy into temp array all values from inner array of 2d array
                for (int i = 0; i < AyHardImg[ iRowCount ].length; i++) {
                    temp[ i ] = AyHardImg[ iRowCount ][ i ];
                }

            //  copy array and make larger on further iteration
                temp  = smCopyArrayInner( temp, iColCount );

            //  use temp array to copy into 2d inner array; included is commented out previous attempt without temp array
                AyHardImg[ iRowCount ]  = temp; //= smCopyArray( AyHardImg[ iRowCount ], iColCount );
                AyHardImg[ iRowCount ][ iColCount ] = ScInLine.nextInt();

                iColCount++;
            }

            iRowCount++;
            ScInLine.close();
        }

    //  test algorithm works as intended by printing hard array to screen
        for ( int i = 0; i < AyHardImg.length; i++ ) {
            for ( int j = 0; j < AyHardImg[i].length; j++ ) {
                System.out.print ( AyHardImg[ i ][ j ] + " " );
            }
            System.out.println();
        }

        ScHardIn.close();

    //  get user response to repeat program
        System.out.print( "Would you like to soften another file (y/n)? " );
        stRepeat1 = ScUser.nextLine().trim().toLowerCase();
    } while ( stRepeat1.equals( "y" ) );


}


/*-----
 * copies inner array, hopefully to solve null
 * pointer exception
 *------------------*/

public static int[] smCopyArrayInner( int[] AyX, int growth ) {

    int[] AyY = new int[ AyX.length  +growth ];

    for ( int i = 0; i < AyX.length; i++ ) {
        AyY[ i ] = AyX[ i ];
    }

    return AyY;
}


/*-----
 * copies outer array, hopefully to solve null
 * pointer exception
 *------------------*/

public static int[][] smCopyArrayOuter( int[][] AyX, int growth ) {

    int[][] AyY = new int[ AyX.length  +growth ][];

    for ( int i = 0; i < AyX.length; i++ ) {
        AyY[ i ] = AyX[ i ];
    }

       return AyY;
    }
}

NPE выглядит следующим образом

Exception in thread "main" java.lang.NullPointerException
  at ex7_imageSmoother.main(ex7_imageSmoother.java:101)

1 Ответ

0 голосов
/ 21 декабря 2018

Спасибо всем, кто прочитал этот вопрос в попытке помочь, но я понял это, "отладив" логику вручную.

По сути, я написал небольшую тестовую программу, которая занималась всего одной строкойвход в одномерный массив и заметил, что мои smCopyArrayOuter и smCopyArrayInner оба стали больше, чем нужно.

по сути, строка

int[][] AyY = new int[ AyX.length  +growth ][];

стала

int[][] AyY = new int[ 1 +growth ][];

, которая решила проблему.

Я также смог покончить с массивом temp и напрямую поработать с AyHardImg, который вы можете увидеть, если посмотрите на репозиторий на gitHub.github.com/q1pt2rx/ex7_imageSmoother.

на момент публикации этого ответа программа является неполной, но эта проблема NPE решена.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...