简体   繁体   English

我如何确保添加到数组的对象的 ID 不存在而不会出现 nullpointerexception?

[英]How do i make sure that the ID of object im adding to array doesn't exist without getting nullpointerexception?

I have an assignment where i am to create a program that manages CDs.我有一个任务,我要创建一个管理 CD 的程序。 I am using switch statement and in the first switch case I have to add a CD to the array but only if a CD with the same ID doesn't already exist in the array.我正在使用 switch 语句,在第一个 switch 情况下,我必须向阵列添加一张 CD,但前提是阵列中不存在具有相同 ID 的 CD。

I've tried with我试过

if (CDid != null && !CDid.equals(CDid.getCdId) {
    cdArray[counter] = cd_obj;
    counter++;
} else {
    counter = cdArray.length-1;
    System.out.println("The array is full");
}

I've also tried a for each loop before the if statement but nothing works.我也在 if 语句之前尝试了 for each 循环,但没有任何效果。 Either i get the nullpointer exception and/or the cd wont add to the array.我得到空指针异常和/或 cd 不会添加到数组中。 I am not allowed to have any nullpointerexceptions in the code and I am stuck on this problem for 2 days now so im hoping someone out there can help me!我不允许在代码中有任何空指针异常,我现在被这个问题困住了 2 天,所以我希望有人能帮助我!

Sorry for any errors ive made this is my first time posting a question on Stacksoverflow很抱歉我犯的任何错误这是我第一次在 Stacksoverflow 上发布问题

The following code is the CD Main class以下代码为CD Main类

public class Cd_main {

    public static void main(String[] args){
    boolean running = true;
    String CDid, CDgenre, CDartist, CDalbum, CDstorageSpot, CDtrackAmount, 
        CDstorageAmount CDprice, searchGenre, deleteCD  ;
    CD[] cdArray = new CD[25];  
    int counter = 0;

    int choice; 
    Scanner scanner = new Scanner(System.in);

    while(running){
           ............................
           ............................
           choice = scanner.nextInt();

           switch(choice){
            case 1:
                System.out.println("......");
                System.out.println("............");
                CDid = scanner.next();  
                CDgenre = scanner.next();   
                CDartist = scanner.next();
                CDalbum = scanner.next();
                CDstorageSpot= scanner.next();
                CDtrackAmount= scanner.next();
                CDstorageAmount = scanner.next();
                CDprice = scanner.next();

                CD cd_obj = new CD(CDid, CDgenre, CDartist, CDalbum, 
                CDstorageSpot, CDtrackAmount, CDstorageAmount, CDprice);                  



               if(CDid.equalsIgnoreCase(CDid.getCdId())){    
               cdArray[counter] = cd_obj;
               counter++;
               }else{
                 counter = cdArray.length-1;
                 System.out.println("The array is full");
              }
             }
             break;
```

The CD class:
```
public class CD {

    public String cd_ID;
    public String genre;
    public String artist;
    public String album;
    public String storageSpot;
    public String trackAmount;
    public String storageAmount;
    public String price;

    public CD() {   
    }
       public CD(String cd_ID, String genre, String artist, String album, 
           String storageSpot, String trackAmount, String storageAmount, 
           String price){
           this.cd_ID = cd_ID;
           this.genre = genre;
           this.artist = artist;
           this.album = album;
           this.storageSpot = storageSpot;
           this.trackAmount = trackAmount;
           this.storageAmount = storageAmount;
           this.price = price;  
    }
    public String getCdId() {
        return this.cd_ID;
    }
    public void setCdId(String cd_ID) {
        this.cd_ID = cd_ID;
    }
    public String getGenre() {
        return this.genre;
    }
    public void setGenre(String genre) {
        this.genre = genre;
    }

    public String getArtist() {
        return this.artist;
    }

    public void setArtist(String artist) {
        this.artist = artist;
    }

    public String getAlbum() {
        return this.album;
    }

    public void setAlbum(String album) {
        this.album = album;
    }

    public String getStorageSpot() {
        return this.storageSpot;
    }

    public void setStorageSpot(String storageSpot) {
        this.storageSpot = storageSpot;
    }

    public String getTrackAmount() {
        return this.trackAmount;
    }

    public void setTrackAmount(String trackAmount) {
        this.trackAmount = trackAmount;
    }

    public String getStorageAmount() {
        return this.storageAmount;
    }

    public void setStorageAmount(String storageAmount) {
        this.storageAmount= storageAmount;
    }

    public String getPrice() {
        return this.price;
    }

    public void setPrice(String price){
        this.price = price;
    }

}

CDid is a String , so CDid.getCdId() makes no sense at all. CDid是一个String ,所以CDid.getCdId()根本没有意义。 You need to go through your entire array to make sure the id doesn't exit.您需要遍历整个数组以确保 id 不会退出。

For instance:例如:

boolean found = false;
for (int i = 0; i < counter; ++i) {
    if (cdArray[i].getCdId().equalsIgnoreCase(CDid)) {
        found = true;
        break;
    }
}
if (found) {
    System.out.println(CDid + " already exists");
} else if (counter >= cdArray.length) {
    System.out.println("The array is full");
} else {
    cdArray[counter] = new CD(CDid, CDgenre, CDartist, CDalbum, 
            CDstorageSpot, CDtrackAmount, CDstorageAmount, CDprice);
    ++counter;
}

Also note that you don't need to create the CD unless you know you will be able to add it in the array.另请注意,除非您知道可以将其添加到阵列中,否则您不需要创建CD

The problem is that you are reading it the wrong way, I assume.问题是你读错了,我想。 As you are dealing with strings, there is no way to separate them from each other without a delimiter, in this case, a newline.在处理字符串时,如果没有分隔符(在本例中为换行符),就无法将它们彼此分开。 You should use Scanner.nextLine , NOT Scanner.next .您应该使用Scanner.nextLine ,而不是Scanner.next Scanner.next reads only one character at a time. Scanner.next只读取一个字符。

Now, for the way you should check for existing ids in the array:现在,对于您应该检查数组中现有 id 的方式:

//For loop to check if any of the elements match the CDId. The variable exists will be
//set to true if it already exists in the array.
boolean exists = false;
if(CDId != null) {
    for(int i = 0; i < cdArray.length; i++) {
        if(cdArray[i] == null) continue;
        if(CDId.equalsIgnoreCase(cdArray[i].getCdId())) {
            exists = true;
            break;
        }
    }
}
if(exists) {
    //If the CDId already exists... (put your own code if you want, such as an error message)
} else {
    //If the id doesn't exist in the array yet, add the cd_obj to the array...
    boolean added = false;
    for(int i = 0; i < cdArray.length; i++) {
        if(cdArray[i] == null) {
            cdArray[i] = cd_obj;
            added = true;
            break;
        }
    }
    //if the cd_obj wasn't added to the array, notify the user.
    if(!added) {
        System.out.println("The array is full");
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将对象添加到数组并获取NullPointerException - Adding object to array and getting NullPointerException 如何检测数组中是否不存在值 - How do I detect if a value doesn't exist in an array 如何确保在显示来自api的无限数据时不会出现NullPointerException。 - How to make sure that NullPointerException doesn't come while showing infinite data from api. 如何确保replaceAll()不会在我的String中留很多空格? - How do I make sure the replaceAll() doesn't leave my String with many spaces? 如果在ManyToOne映射中不存在,如何加载id,而不是对象,如何加载 - How to load the id, but not the object if it doesn't exist in a ManyToOne mapping 我不知道为什么我得到错误/警告“必需:找到 T[]:Object[]”,以及“T 扩展类 Stack 中声明的对象” - im not sure why im getting the error/warning "required: T[] found: Object[]", and " T extends Object declared in class Stack" 我需要将面板拆分2次,我不确定该怎么做 - I need to split my panels 2 times and Im not sure how to do it 将Ignite与mysql一起用作第三方持久性存储时,如何确保缓存键和对象ID相同 - How do I make sure cache key and object id is the same when using Ignite together with mysql as a 3rd party persistent storage 我有一个缓存Servlet过滤器,如果在响应上设置了cookie,如何确保它不发送缓存头? - I have a caching Servlet Filter, How do I make sure it doesn't send caching headers if there are cookies set on the response? 使用对象数组获取NullPointerException - Getting NullPointerException with Object Array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM