Как я могу исправить свой код, чтобы дать правильный вывод вместо того, чтобы ничего не давать? - PullRequest
0 голосов
/ 10 января 2020

Когда я запускаю свой код, я ничего не получаю как вывод. Я подозреваю, что мой код останавливается на этом методе:

  public void deleteAt(int position)
  {
      if (position >= 0)
      {
          for (int i = position; i < theArray.length; i++)
          {
              theArray[i] = theArray[i + 1];
          }
      }
  }

Я думаю, что он останавливается на вышеуказанном методе, потому что этот код:

  public int positionOf(char value)
  {
      //Search the list to find the value, if found return the position, if not, return -1
      for (int i = 0; i < size(); i ++)
      {
          if (theArray[i] == value)
          {
              return i;
          }
      }
      return -1;
  }

возвращает только -1. Если я удаляю возврат -1; тогда Java считает, что произошла ошибка, потому что нет возвращаемого состояния. Я попытался добавить еще, но я все еще получаю ту же ошибку.

Это весь код:

/** The interface for our List (Abstract Data Type) */
interface IList {
/** Adds the given value to the end of the list */
void append(char value);

/** Adds the given value to the beginning of the list */
void prepend(char value);

/** Deletes the container at the given position (a container holds a value) */
void deleteAt(int position);

/** Returns the number of values currently in our list */
int size();

/** Retrieves the value at the given position */
char getValueAt(int position);

/** Searches for the FIRST occurence of a given value in our list.
* If found, it returns the position of that value.
* If not found, it returns -1 */
int positionOf(char value);
}


/** Array implementation of our List */
class ListAsArray implements IList {
    // initialize array to a size of 30 elements
    // this will prevent the need to resize our array
    char[] theArray = new char[30];

    public void append(char value)
    {
      //Count until you find a place in the array that is empty, then insert
      for (int i = 0; i < theArray.length; i ++)
      {
          if (theArray[i] == 0)
          {
              theArray[i] = value;
          }
      }
    }
    public void prepend(char value)
    {
      //Count until you find a empty value
      for (int i = 0; i < theArray.length; i ++)
          {
              if (theArray[i] == 0)
              {
                  //Once you find the empty value move everything over
                  for(int j = theArray.length; j != 0; j--)
                  {
                      theArray[i] = theArray[i + 1];
                  }
              }
          }
          //Finally you want to actually add in the number in the first position
          theArray[0] = value;
    }

      public void deleteAt(int position)
      {
          if (position >= 0)
          {
              for (int i = position; i < theArray.length; i++)
              {
                  theArray[i] = theArray[i + 1];
              }
          }
      }
      public int size()
      {
          //Count until you find a place in the array that is empty, then return the number
          int count = 0;
          for (int i = 0; i < theArray.length; i ++)
          {
              if (theArray[i] == 0)
              {
                  return count;
              }
              count ++;
          }
          return 0;
      }
      public char getValueAt(int position)
      {
          return theArray[position];
      }
      public int positionOf(char value)
      {
          //Search the list to find the value, if found return the position, if not, return -1
          for (int i = 0; i < size(); i ++)
          {
              if (theArray[i] == value)
              {
                  return i;
              }
          }
          return -1;
      }
    }


/** Singly Linked List implementation of our List */
class ListAsLinkedList implements IList {
  //Point to first node and second node
  private Node head;
  private Node tail;
  //Constructor sets head and tail to null
  public void LinkedList() 
  {
    head = null;
    tail = null;
  }
  public void append(char value) 
  {
    //Wrap the data in a node
    Node temp = new Node(value);
    //Make this the first node if no other nodes
    if (tail == null) 
    {
      //Set tail to new node
      tail = temp;
      //Set head to new node
      head = temp;
    }
    else 
    {
      //Set new node to be after current end
      tail.setNext(temp);
      //Set as new tail 
      tail = temp;
    }
  }
  public void prepend(char value)
  {
    //Wrap the data in a node
    Node temp = new Node(value);
    //Make this the first node if no other nodes
    if (tail == null) 
    {
      //Set tail to new node
      tail = temp;
      //Set head to new node
      head = temp;
    }
    else 
    {
        temp.next = head;
        head = temp;
    }
  }
  public void deleteAt(int position)
  {
      //Make the head node the next node if its the first one
      if(position == 0)
      {
          head=head.next;
      }
      //If that wasn't the case...
      Node current = head;
      for(int i = 0; i < position-1; i++)
      {
          current = current.next;
      }
      current.next = current.next.next;
      if(current.getNext() == null)
      {
          tail = current;
      }
  } 
  public int size()
  {
      Node temp = head;
      for (int i = 0; i != 103; i++)
      {
          if (temp == tail)
          {
              return i;
          }
      }
      return 0;
  }
  public char getValueAt(int position)
  {
      Node temp=head;
      for(int i=0; i < position; i++)
      {
          temp=temp.next;
      }
      return temp.data;
  }
  public int positionOf(char value) 
  {
    //Start at the beginning
    int position = 0;
    Node current = head;
    //Look until we find target data
    while (current.getData() != value) 
    {
      //Move to next node
      current = current.getNext();

      //Increment position
      position++;
    }

    //return position found
    return position;
  }
}


/** A singly linked list node for our singly linked list */
class Node {
  //The node data and link to next node
  public char data;
  public Node next;
  //Constructor
  public Node(char data) 
  {
    this.data = data;
    this.next = null;
  }
  //Accessor
  public char getData() 
  { 
    return data;
  }
  //Accessor
  public Node getNext() 
  {
    return next;
  }
  //Mutator
  public void setData(char data) 
  {
    this.data = data;
  }
  //Mutator
  public void setNext(Node next) 
  {
    this.next = next;
  }
}

Это главное:

/** contains our entry point */
public class Main {
  /** entry point - DO NOT CHANGE the pre-existing code below */
  public static void main(String[] args) {
    int[] numbers = {105,116,112,115,65,58,47,47,116,105,110,121,88,117,114,108,46,99,111,109,47};
    int[] numbers2 = {97,59,111,53,33,111,106,42,50};
    int[] numbers3 = {116,104,32,111,116,32,111,71};


    /// List as an Array
    IList array = new ListAsArray();

    // add values
    for(int num : numbers) {
      array.append((char)num);
    }
    for(int num : numbers3) {
      array.prepend((char)num);
    }

    // delete some values
    int position;

    position = array.positionOf((char)105);
    array.deleteAt(position);

    position = array.positionOf((char)65);
    array.deleteAt(position);

    position = array.positionOf((char)88);
    array.deleteAt(position);

    // print em
    position = 0;
    while (position < array.size()) {
      System.out.print(array.getValueAt(position));
      position++;
    }


    /// List as a Linked List
    IList linkedList = new ListAsLinkedList();

    // add values
    for(int num : numbers2) {
      linkedList.append((char)num);
    }
    linkedList.prepend((char)55);
    linkedList.prepend((char)121);

    // delete some values
    position = linkedList.positionOf((char)59);
    linkedList.deleteAt(position);

    position = linkedList.positionOf((char)33);
    linkedList.deleteAt(position);

    position = linkedList.positionOf((char)42);
    linkedList.deleteAt(position);

    // print em
    position = 0;
    while (position < linkedList.size()) {
      System.out.print(linkedList.getValueAt(position));
      position++;
    }

    System.out.println();

    // ???

  }
}

Должна быть выведена ссылка, относящаяся к следующей части моего назначения.

1 Ответ

1 голос
/ 10 января 2020

Метод size() всегда возвращает 0 в соответствии с вашими данными.

size() метод согласно вашему коду не дает вам длину массива для повторения. Поэтому вы должны использовать длину массива, т.е. theArray.length в positionOf() методах для l oop вместо size() метода.

...