簡體   English   中英

難以將鍵值對添加到我的 HashMap

[英]Having difficulty adding key-value pairs to my HashMap

我正在嘗試使用HashMap來存儲鍵值對,其中鍵是字母數字字符串,值是另一個名為 Account 的 class 的堆棧。 我現在正在為 add 方法編寫代碼,但遇到了一個問題。 由於某種原因,代碼在評估HashMap中是否已經存在時停止。

如果 VIN 與 object 帳戶的 VIN 不匹配,該方法應該做的是拋出異常,如果不是這種情況,它應該檢查 VIN 是否已經在HashMap中,如果是應該添加帳戶 ZA8CFDE6331BD4B662AC1與 VIN 關聯的堆棧,如果不存在,則應創建堆棧,將值添加到堆棧並將密鑰堆棧對添加到HashMap

這是我到目前為止所嘗試的:

//importing HashMap
import java.util.HashMap;  
{ 
//Creating HashMap
private HashMap<String, Stack<Account>> records;   

//add method
public void add(String VIN, Account value) throws Exception
    { 

        if(!VIN.equals(value.getVIN())) 
        {  
            System.out.println("Something went wrong :/");
            throw new Exception("VIN does not match account");  
        }  
        else if(records.containsKey(VIN)) 
        { 
            System.out.println("VIN exists, adding to record");
            records.get("VIN").add(value); 
            System.out.println("Success!");
        } 
        else 
        {  
            System.out.println("New account made, record added!");
            Stack<Account> stack = new Stack<Account>(); 
            stack.add(value);
            records.put(VIN, stack); 
            System.out.println("Success!");
        }
    } 
   //Driver 
   public static void main(String[] args) 
    { 
        CVR hello= new CVR(); 
        try 
        {  
            Account abdcg=new Account("adsj4jandnj4", "abdcg", "perfect record");  
            Account abdcg1=new Account("adsj4jandnj4","abdcg1", "Fender Bender");
            /////
            hello.add("adsj4jandnj4", abdcg); 
            hello.add("adsj4jandnj4", abdcg1);
        } 
        catch (Exception e) 
        {
            // TODO Auto-generated catch block
            e.getMessage();
        }
    }
} 

請注意,我對此很陌生,我才剛剛了解 HashMaps,這是我第一次使用它們,任何幫助將不勝感激!

**編輯:這是所要求的完整 CVR 代碼:

import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;  
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Stack; 
import java.util.Random; 
import java.util.*;

public class CVR 
{
    //this will be used to generate random alpha numeric numbers
    private final static String alphaNumeric="ABDCEFGHIJKLMNOPQRSTUVWXYZ0123456789"; 
    //key
    private String VIN; 

    //threshold (determines which ADT to use)
    private int threshold; 

    //length of key
    private int VINLength; 

    //this is an object of Archive which will hold the data associated with VIN
    private Account value; 

    //TBD
    //private Collection<Account> activeVINS;

    //HashMap to store all the key-value pairs 
    //the value come in the form of a stack because, 
    //multiple events can be associated with the same  
    //VIN, and must be shown in reverse-chronological order
    private HashMap<String, Stack<Account>> records; 

    //This will keep track of all VINs and make sure  
    //none of them are repeated
    private HashSet<String> VINRecorder;

    //default constructor
    public CVR() {}

    //parameterized constructor for CVR, takes VIN 
    //and adds it to VINRecorder
    public CVR (String VIN) 
    {
        this.VIN=VIN; 
        records=new HashMap<>(); 
        VINRecorder.add(VIN);
    } 

    //accessors and mutators 
    //VIN getters and setters
    public String getVIN() 
    { 
        return VIN;
    } 
    public void setVIN(String VIN) 
    { 
        this.VIN=VIN; 
        VINRecorder=new HashSet<>(); 
        VINRecorder.add(VIN);
    } 
    //threshold getters and setters 
    public int getThreshold() 
    { 
        return threshold;
    } 
        //for this one we have to keep in mind the restriction set 
        //on us in the instructions
    public void setThreshold(int threshold) throws Exception
    { 
        if(threshold<100 || threshold>900000) 
        { 
            //System.out.println("Invalid input for threshold"); 
            throw new Exception("Invalid input for threshold");
        } 
        else 
        { 
            this.threshold=threshold;
        }
    } 
    //VINLength getters and setters 
    public int getVINLength() 
    { 
        return VINLength;
    } 
        //again for this one. we need to take the 
        //instructions into account for this special 
        //case 
    public void setVINLength(int VINLength) throws Exception 
    { 
        if(VINLength<10 || VINLength>17) 
        { 
            throw new Exception("Invalid input for VIN length");    
        } 
        else 
        { 
            this.VINLength=VINLength;
        }
    } 


    //Now onto the methods 
    //Generate method 
    //This method should randomly generate a sequence 
    //containing n new non-existing valid keys 
    //***Must determine whether the output is a sequence or not
    public String generate(int size) throws Exception 
    { 

        char[] Arr= alphaNumeric.toCharArray(); 
        String[] ender=new String[size];


        //generating random number between 10 and 17 
        Random r= new Random(); 
        int low=10; 
        int high=17; 
        for(int x=0; x<size;x++) 
        {  
            int highLow=r.nextInt(high-low)+10;
            StringBuilder newString=new StringBuilder();
            //making string between length of 10 and 17 randomly
            for(int i=0; i<highLow; i++) 
            { 
                newString.append(Arr[new Random().nextInt(Arr.length)]); 
            } 
            /////////////////// 
            String newVIN=newString.toString(); 
            //System.out.println(newVIN);  


            //This must be further explored, I do not know why, 
            //but for some reason it does not work if the first 
            //condition is not there, to be explored
            if(newVIN!=null) 
            { 
            } 

            //stops here for some reason, must find out why, something is wrong with this statement
            else if(VINRecorder.contains(newVIN)) 
            {  
                x--;
            }  
            else 
            { 
                ender[x]=newString.toString(); 
            }   

            ender[x]=newString.toString();

        }   
        //System.out.println("hello");
        System.out.println(Arrays.toString(ender));
        return Arrays.toString(ender);
    }

    //method allKeys 
    //this method should return all keys as a sorted 
    //sequence in lexicographic order 
    //the plan here is to use
    /**
    public LinkedList<Account> allKeys()
    {

    } 
    **/

    //add method 
    //****must check to see if must be resized later
    public void add(String VIN, Account value) throws Exception
    { 

        if(!VIN.equals(value.getVIN())) 
        {  
            System.out.println("Something went wrong :/");
            throw new Exception("VIN does not match account");  
        }  
        else if(records.containsKey(VIN)) 
        { 
            System.out.println("VIN exists, adding to record");
            records.get(VIN).add(value); 
            System.out.println("Success!");
        } 
        else 
        {  
            System.out.println("New account made, record added!");
            Stack<Account> stack = new Stack<Account>(); 
            stack.add(value);
            records.put(VIN, stack); 
            System.out.println("Success!");
        }
    } 




    //driver method
    public static void main(String[] args) 
    { 
        CVR hello= new CVR(); 
        try 
        {
            //System.out.println("hello");
            //hello.generate(5);  
            Account abdcg=new Account("adsj4jandnj4", "abdcg", "perfect record");  
            Account abdcg1=new Account("adsj4jandnj4","abdcg1", "Fender Bender");
            /////
            hello.add("adsj4jandnj4", abdcg); 
            hello.add("adsj4jandnj4", abdcg1);
        } 
        catch (Exception e) 
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

您在此處使用硬編碼字符串"VIN"

        System.out.println("VIN exists, adding to record");
        records.get("VIN").add(value); 
        System.out.println("Success!");

它應該是變量 VIN 的值:

        records.get(VIN).add(value); 

您很可能會拋出 NullPointerException,因為 records.get records.get("VIN")會返回null但您的異常處理程序會默默地“吞下”所有異常。 讓 catch 塊打印一些東西,以便下次你會收到警告。

    catch (Exception e) {
        e.printStackTrace();
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM