简体   繁体   English

在Hashmap中搜索

[英]Search in Hashmap

Using for loop to compare the input value with the hashmap if it matches any value in the hash-map then the code prints all the related values with that time. 如果输入值与hashmap中的任何值匹配,则使用for循环将输入值与hashmap进行比较,然后代码将打印所有相关值。

The result shows out for me NULL 结果显示我为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);
        }}

Class 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 );

    }
    }

}

Following the 3 steps (ignoring the Json part) u mentioned and reusing some of your code i can provide u this code: 按照你提到的三个步骤(忽略Json部分)并重用你的一些代码,我可以提供你的代码:

Main.java : 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 : 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;
    }
}

It might not fit exactly your needs but it can be a help. 它可能不完全符合您的需求,但它可以是一个帮助。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM