java.lang.NullPointerException - в моем коде нет ничего, что могло бы вызвать его, но оно все равно появляется - PullRequest
0 голосов
/ 27 сентября 2019

Здравствуйте, моя задача - написать класс, в котором я должен иметь метод executeCommands, который выполняет команды для черепахи, такие как

1 - Pen up 2 - Pen down 3 - Повернуть направо на 90° 4 - Поворот налево на 90 ° 5, d - Перемещение в текущем направлении «d» пробелы 6 - Отображение (печать) текущего состояния этажа 9 - Указывает конец программы (ничего после этой команды не является частьюи должен игнорироваться)

Хотя я написал весь необходимый код для executeCommands, я все еще получаю ошибку NullPointerException, даже если я не вижу нулевых значений в моем коде.

public boolean executeCommands()
{
    int commandNumber = 0; // the current position in the array
    int direction = 0; // the direction the turtle is facing
    int distance = 0; // the distance the turtle will travel
    int command; // the current command
    boolean penDown = false; // whether the pen is up or down
    xpos = 0;
    ypos = 0;
    command = commandArray[ commandNumber ][ 0 ];
    // continue executing commands until either reach the end
    // or reach the max commands

   //System.out.println("Executing...");
   // determine what command was entered
   // and perform desired action
   switch ( command )
   {
      case 1: // pen down
         penDown = false;
         break;
      case 2: // pen up
         penDown = true;
         break;
      case 3: // turn right
         direction = turnRight( direction );
         break;
      case 4: // turn left
          direction = turnLeft( direction );
         break;
      case 5: // move
         distance = commandArray[ commandNumber ][ 1 ];
         movePen( penDown, floor, direction, distance );
         break;
      case 6: // display the drawing
         System.out.println( "\nThe drawing is:\n" );
         printArray( floor );
         break;
   }  // end switch
        command = commandArray[ ++commandNumber ][ 0 ];  // end while
     return false;
      } // end method executeCommands
      // method to turn turtle to the right
       public int turnRight( int d )
       {
     return ++d > 3 ? 0 : d;
  } // end method turnRight
  // method to turn turtle to the left
  public int turnLeft( int d )
  {
    return --d < 0 ? 3: d;
      // To do
  } // end method turnLeft
  // method to move the pen
  public void movePen( boolean down, int a[][], int dir, int dist )
  {
     int j; // looping variable
     // determine which way to move pen
     switch ( dir )
     {
        case 0: // move to right
           for ( j = 1; j <= dist && ypos + j < SIZE; ++j )
         if ( down )
            a[ xpos ][ ypos + j ] = 1;
      ypos += j - 1;
      break;
   case 1: // move down
      // To do
      break;
   case 2: // move to left
      // To do
      break;
   case 3: // move up
      // To do
      break;
     } // end switch
  } // end method movePen
  // method to print array drawing
  public void printArray( int[][] a )
  {
     // display array
     for ( int i = 0; i < SIZE; ++i )
     {
             for ( int j = 0; j < SIZE; ++j )
         System.out.print( ( a[ i ][ j ] == 1 ? "*" : "-" ) );
        System.out.println();
     } // end for
  }
 }
This is kind of output I should be getting.
2 5,12 3 5,12 3 5,12 3 5,12 1 6 9
2   5 12 3 5 12    3 5 12 3 5,12  1  6 9
2  5  12  3  5  12  3  5  12  3  5  12  1  6  9
2, 5,12 3, 5,12 3, 5,12 3, 5,12 1, 6, 9, 24,
2, 5  12 3,  5, 12,  3 5, 12,  3 5,12 1 6     9

1 Ответ

0 голосов
/ 27 сентября 2019

в какой строке появляется ошибка?Я могу только догадываться, что эта строка:

command = commandArray[ commandNumber ][ 0 ];

- это commandArray , объявленный как глобальный или переданный executeCommands ()?Я не могу понять, как команда сможет принять эту переменную ...

попробуйте передать массив (я предполагаю, что это тип int), например:

public boolean executeCommands(int[][] commandArray) { //your code }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...