在Hashmap中搜索

时间:2017-03-11 08:50:35

标签: java json hashmap java.util.scanner

如果输入值与哈希映射中的任何值匹配,则使用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 );

    }
    }

}

1 个答案:

答案 0 :(得分:0)

按照3个步骤(忽略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;
    }
}

它可能不完全符合您的需求,但它可以提供帮助。