1

我正在尝试模拟生产系统,现在我无法获取值并将值传递给位于不同类的 TreeMap。

为了简要解释我打算做什么,我将创建一个面板,其中有一些文本面板来保存值(用于添加到系统中的零件数量)和一个表格,其中工作站的数量和参数系统将被设置。当我运行它时,应该存储这些值以供进一步处理。

在上一个问题上,建议我使用 TreeMaps 来存储这些值,例如:

Station[num][type][avg_time][posx][posy][state]
Part[num][type][state]

这是我到目前为止编码的内容:

爪哇

import java.awt.*;
import javax.swing.*;    

public class L extends JFrame {

    public static void main(String[] args) {


      SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            L l = new L();

            TMap t = new TMap();
            t.Station("num", 127);
            t.Station("type", 3);
            //System.out.println("Entryset: " + t.keySet());
            //System.out.println("Entryset: " + t.Station() + "\n");
         }
      });

    }

 } 

TMap.java

import java.util.*;

public class TMap {
    //public TreeMap <String, Integer>St = new TreeMap<String, Integer>();
    public int num_atrib = 6;
    public static TreeMap<String, Integer> Station(String s,int i) {
        TreeMap <String, Integer>St = new TreeMap<String, Integer>();
        St.put(s,i);
        System.out.println("Now the tree map Keys: " + St.keySet());
        System.out.println("Now the tree map contain: " + St.values());
        return St;
    }
} 

这是输出:

Now the tree map Keys: [num]
Now the tree map contain: [127]
Now the tree map Keys: [type]
Now the tree map contain: [3]

我有两个问题,首先,这是正确的方法吗,因为我看到输出的地图应该是 [num, type] 和键 [127, 3] 对吗?

其次,我以后如何从 L 类的 TMap 获取参数,因为 t.keySet() 例如到目前为止不会检索任何东西!

希望我说清楚了,在此先感谢您的帮助。

4

1 回答 1

1

首先,每次调用 TMap.Station 时都会创建一个新的 TreeMap。尝试将 TreeMap 作为字段并在构造函数中对其进行初始化。那应该为您提供包含两个键/值对的地图。

回答你的第二个问题,你有什么理由不能让 TMap 成为一个字段而只是创建方法来访问和设置?如果您只在一个函数中实例化它,它会在该函数退出后立即消失(加上它的范围只会在该函数中)。

编辑:回应评论......怎么样

编辑编辑:为吸气剂添加粗略的轮廓。如果你想要一个 put() 之类的东西,它会以类似的方式工作。

import java.awt.*;
import javax.swing.*;
import java.util.Set;

public class L extends JFrame {
    private TMap t;

    public L() {
        t = new TMap();
    }

    public Set<String> getKeySet() {
        return t.getKeySet();
    }

    public Integer get(String s) {
        return t.get(s);
    }

    // your main method as before
}

import java.util.*;

public class TMap {
    private TreeMap<String, Integer> St;
    private int num_atrib = 6;

    public TMap() {
        St = new TreeMap<String, Integer>();
    }

    public Set<String> getKeySet() {
        return St.keySet();
    }

    public Integer get(String s) {
        return St.get(s);
    }

    public static TreeMap<String, Integer> Station(String s,int i) {
        St.put(s,i);
        System.out.println("Now the tree map Keys: " + St.keySet());
        System.out.println("Now the tree map contain: " + St.values());
        return St;
    }
}
于 2012-07-11T16:17:44.797 回答