0

これがすべて理解するのが難しいと思われる場合は申し訳ありませんが、私はプログラミングが初めてで、いくつかの本やWebサイトを調べました.私の理解から、私がやろうとしていることはうまくいくはずです. 私が取り組んでいる課題は、クラスを呼び出すクラスです。すべてのコードをここに入れることなく、不明確な領域でできるだけ具体的にしようとします。null ポインターの例外は、次の特定のコード行で発生します。

  if(CDList[i].getArtist().equals(artist) == true)

//CDList は CD オブジェクトの配列です (別のクラスで作成されます)

//getArtist() は、文字列を返す CD クラスのメソッドです。

// equals() のアーティストは、ユーザーが入力した Scanner オブジェクトであり、文字列でもあります

この特定のメソッドのポイントは、配列 CDList を検索し、保存されているアーティスト文字列をスキャンされたアーティスト文字列と比較し、タイトルについても同じであることです。見つかった場合、配列のその部分の内容が削除されます。それが役立つ場合は、メソッドの残りの部分を次に示します。

void delete()
{
   Scanner input = new Scanner(System.in);
   System.out.println("Enter artist and title to be deleted: ");
   String artist = input.nextLine();
   String title = input.nextLine();

for(int i = 0; i <= numOfCDs; i++)
{
   if(CDList[i].getArtist().equals(artist) == true)
   {
      for(int j = 0; j <= numOfCDs; j++)
      {
         if(CDList[j].getTitle().equals(title) == true)
         {
            System.out.println("Found CD: " + CDList[j].getArtist() + " " +                 
               CDList[j].getTitle());
            System.out.println("Would you like to delete it? Y/1 N/0 ");

        if(input.nextInt() == 1)
            {
               CDList[j] = null;
               numOfCDs--;
            }
         }
         else
            System.out.println("CD not found.");
      }
    }
    else
       System.out.println("CD not found.");
 }
}

申し訳ありませんが、これが残りのコードです。あまりにも多いと思ったので、省略します。

CD クラス:

package assignment3;
public class CD 
{
    public String artist;
    public String title;
    private tracklist listOfTracks = new tracklist();

CD(String artistName, String titleName)
{
    artist = artistName;
    title = titleName;
}

public String getArtist()
{
    return artist;
}

public String getTitle()
{
     return title;
}

public boolean addTrack(String trackInfo)
{
     boolean result = false;
     if(listOfTracks.add(trackInfo) == true)
         result = true;
     return result;
}

public int numTracks()
{
    int count = listOfTracks.count();
    return count;
}

public void display()
{
    System.out.println(" ");
    System.out.println(getArtist() + " : " + getTitle());
    listOfTracks.display(7);
}
}

トラックリスト クラス:

package assignment3;
public class tracklist 
{
    public String[] tracks;
    public int numElements;

    tracklist()
    {
        tracks = new String[99];
        numElements = 0;
    }

    public boolean add(String track)
    {
        boolean result = true;
        int index = 0;

        while(tracks[index] != null)
        {
           index++;
        }    

        tracks[index] = track;
        numElements++;
        if(numElements > 99)
            result = false;
        return result;
    }

    public int count()
    {
        return numElements;
    }

    public void display(int indent)
    {
        for(int i = 1; i < numElements; i++)
        {
            System.out.print(i);
            if(i >= 10)
            {
                 for(int j = 0; j < (indent - 1); j++)
                 {
                     System.out.print(" ");
                 }
            } 
            else
            {
                 for(int j = 0; j < indent; j++)
                 {
                     System.out.print(" ");
                 }
            }
            System.out.println(tracks[i]);
         }
    }    
   }

CDList クラス:

package assignment3;
import java.util.Scanner;
public class CDList 
{
   public int numOfCDs;
   private CD[] CDList;
   private int front,rear;

   CDList(int size)
   {
       CDList = new CD[size];
       numOfCDs = 0;
       front = 0;
       rear = size - 1;
   } 

   boolean add()
   {
       boolean result;
       Scanner input = new Scanner(System.in);
       System.out.println("Enter the Artist Name and CD Title: ");
       CD userCD = new CD(input.nextLine(), input.nextLine());
       System.out.println("Enter the number of tracks: ");
       int trackNumber = input.nextInt();
       System.out.println("Enter your track titles: ");

       for(int i = 0; i <= trackNumber; i++)
       {
           userCD.addTrack(input.nextLine());
       }

       if(rear == front)
           result = false;
       else
       {
           if(CDList[rear] != null)
           rear--;
           else
               CDList[rear] = userCD;
           result = true;
       }
       return result;
   }

   void delete()
   {
       Scanner input = new Scanner(System.in);
       System.out.println("Enter artist and title to be deleted: ");
       String artist = input.nextLine();
       String title = input.nextLine();

       for(int i = 0; i <= CDList.length - 1; i++)
       {
           if((CDList[i].getArtist().equals(artist)) &&    
             (CDList[i].getTitle().equals(title)))
           {
               System.out.println("Found CD of: " + CDList[i].getArtist() + " " +                 
                 CDList[i].getTitle());
               System.out.println("Would you like to delete it? Y/1 N/0 ");
               if(input.nextInt() == 1)
               {
                   CDList[i] = null;
                   numOfCDs--;
               }
           }
           else
               System.out.println("CD not found.");
       }
   }

   void SortArtist()
   {
       CD temp = new CD(" ", " ");
       for(int i = 0; i < numOfCDs; i++)
           if(CDList[i].getArtist().compareTo(CDList[i + 1].getArtist()) < 0)
           {
               temp = CDList[i];
               CDList[i] = CDList[i + 1];
               CDList[i + 1] = temp;
           }
   }

   void SortTitle()
   {
       CD temp = new CD(" ", " ");
       for(int i = numOfCDs; i > 0; i--)
       {
           int x = 0;
           for(int j = 1; j <= i; j++)
           {
               if(CDList[i].getTitle().compareTo(CDList[i + 1].getTitle()) < 0)
                   x = j;
           }
           temp = CDList[x];
           CDList[x] = CDList[i];
           CDList[i] = temp;
       }
   }

   void Display()
   {
      for(int i = 0; i <= numOfCDs; i++)
      {
          while(CDList[i] == null)
              i++;
          CDList[i].display();
      }
   }

   int size()
   {
       return numOfCDs;
   }
}
4

5 に答える 5

4
if(CDList[i].getArtist().equals(artist) == true)

NPE を取得している場合は、次の可能性があります。

  1. CDList無効です
  2. CDList[i]無効です
  3. CDLIst[i].getArtist()null を返します
  4. クラスはArtistオーバーライドequals()され、NPE を引き起こすバグがありますが、その場合、NPE は のステートメントを指しequals()ます。

Artistをオーバーライドするかどうかを確認できるようにクラスを表示しequals()ておらず、例外がスローされた場所を正確に確認できるようにスタック トレースを投稿していません。

他の人がコメントしているように、これ== trueは余分です。

于 2013-03-12T03:01:30.610 に答える
0

それを見つけた!コメントありがとうございます。私はあなたが推奨するいくつかの変更を加えました。問題は、CDList[i]がnullであることにありました。if(CDList [i] == null)を実装した後、続行します。ご入力いただきありがとうございます。– </ p>

于 2013-03-12T14:48:56.073 に答える
0

LinkedList<CD>またはArrayList<CD>の代わりに使用することをお勧めしCD[]ます。

これにより、次のようにアイテムを簡単に削除できます。

LinkedList<CD> cdList = new LinkedList<CD>();
// add items with cdList.add(...);
Iterator<CD> cdListIterator = cdList.iterator();

// Loop while the list still contains elements.
while (cdListIterator.hasNext()) {
    CD thisCd = iterator.next();
    // do some operation on the cd to tell whether you want to delete it
    // for example:
    if (thisCd.getArtist().equals(artist) && thisCd.getTitle().equals(title)) {
        iterator.remove(); // it's that simple
        // Don't have to mess with `cdCount--` or anything.
    }
}

そして、一部の人がコメントしているように、必要はありませんa.equals(b) == true; あなたはただ使うことができますa.equals(b)

于 2013-03-12T03:01:46.083 に答える
0

There are a number of problems here.

The immediate cause of your NPE is that the inner loop "removes" a CD from the list by assigning it to null, and then the outer loop tries to test the CD at the position you just removed. Since it is null, you then attempt to call null.getArtist() which NPEs.

The first thing to note is that you only need one loop. The loop body should test that the CD you are looking at has the same title AND artist ...

The next thing to note is that getting rid of the extra loop is not enough. If the delete() method is called more than once, the second call is likely to encounter a null entry that was produced by the first call ... and you will get an NPE as before. The tests should check for a null before they try to get the title / artist information; e.g.

CD cd = cdList[i];
if (cd != null && 
    cd.getArtist().equals(artist) &&
    cd.getTitle().equals(title)) {
    // ...
}

At this point a design problem becomes apparent. These null values in the array are a bad idea. There are three fixes:

  • You could remove the CDs by creating a new array one element smaller ... and copy across all CDs apart from the one you are deleting.

  • You could add a cdListSize field, and arrange that it gives you the number of valid entries in the list. Then (and this is the important bit), when you delete an entry from the list, move the current last entry to the place where the deleted entry was and decrement the cdListSize. If you do that consistently, the null entries will all be at the end, and you can iterate from zero to cdListSize - 1 to get the non-null entries.

  • Best of all, use a List rather than an array to represent the CD list. The List API provides a method for removing the entry at a given position. The method really removes it ... it doesn't just set it to null.

Finally, you may need to take a step back and look at the larger application. Is the CD list supposed to be persisted; e.g. so that it is still available when your application restarts? Is it likely to be large; e.g. too large to fit into memory? Are you likely to want to do complicated queries on the CD list? All of these things would suggest that you should use a database rather than an in-memory data structure.

(However, with the extra code you've just added, it is clear that would be beyond the scope of your assignment.)

于 2013-03-12T03:38:45.107 に答える