簡體   English   中英

在Hashmap中搜索

[英]Search in Hashmap

如果輸入值與hashmap中的任何值匹配,則使用for循環將輸入值與hashmap進行比較,然后代碼將打印所有相關值。

結果顯示我為NULL

       System.out.println("Please enter time :");
        Scanner scan = new Scanner(System.in);
        String value = scan.nextLine();//Read input-time
        Measurement measurement = measurements.get(value);//there can only be 1 Measurement for 1 time
        if(measurement != null){
            System.out.println(measurement);
        }}

等級測量:

    public void getTimeInfo(String value)
    {

        value = Measurements.get(time);
        if (value == null) {
            throw new MeasurementException();
        }

        System.out.println("The detailed info : " + this.time + "-" + this.temp+ " "+ this.wind+ "-" + this.humid );

    }
    }

}

按照你提到的三個步驟(忽略Json部分)並重用你的一些代碼,我可以提供你的代碼:

Main.java

public class Main {

    static HashMap<String, Measurement> measurements = new HashMap();

    public static void main(String[] args) {
        for (int i = 0; i < 3; i++) {//Create 3 measurements
            String time = ""+i;
            measurements.put(time, new Measurement(time, (float) i, (float) i, (float) i));
        }

        System.out.println("Please enter time :");
        Scanner scan = new Scanner(System.in);
        String value = scan.nextLine();//Read input-time
        Measurement measurement = measurements.get(value);//there can only be 1 Measurement for 1 time
        if(measurement != null){
            System.out.println(measurement);
        }

    }
}

Measurement.java

public class Measurement {
    String time ;
    Float temp;
    Float wind;
    Float humid;
    int iD;   

    public Measurement(String d, Float t, Float w, Float h){
        this.time = d;

        this.temp = t;
        this.wind = w;
        this.humid = h;
    }

    @Override
    public String toString() {
        return "The detailed info : " + this.time + "-" + this.temp+ " "+ this.wind+ "-" + this.humid;
    }
}

它可能不完全符合您的需求,但它可以是一個幫助。

暫無
暫無

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

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