【问题标题】:Java Hashmap returning a value from a given key, using randomJava Hashmap 从给定键返回一个值,使用随机
【发布时间】:2011-07-29 13:07:16
【问题描述】:

我在让我的程序运行方面遇到了一些问题。我创建了一个具有设置的哈希图,该哈希图可以保存 4 个键/值对。

现在每个键 (0,1,2,3) 都附加到代表颜色(“白色”、“红色”...等)的字符串“值”。

现在我使用 random 给我一个从 0 到 3 的随机数,我将其分配给一个 int 变量。

然后我使用这个变量来查看集合是否包含这个 int 键(它会),然后我想将与该键关联的值分配给一个 String 变量,然后我将在一个方法中使用它来更改GUI 面板的颜色(触发事件时生成随机颜色)。

// changing yellow with the String variable representing the value 
// from the hashmap found by matching the key with the random int.
centerPanel.setBackground(Color.yellow);  

谁能帮帮我?到这里已经快 12 点了,可能早上就能弄明白,但脑子里一片空白!!

【问题讨论】:

  • “使用随机返回值”让我想做public int hashCode() { return (int)(Math.random() * Integer.MAX_VALUE); } :-)

标签: java random key hashmap


【解决方案1】:

对于任何对我如何解决此问题感兴趣的人(感谢此处其他人的帮助和谷歌上的教程):

    // fields
    private Color1[] colors = { Color1.red, Color1.green, Color1.blue, Color1.yellow };
    private int a2;
    private String getRandomColor;

    //constructor calling methods to generate a random value to 'a2' (0 to 3) and then setting variable a2 to the color as a string

    public SamTester()
    {
        setA2();
    }

    public void setA2()
    {
        a2 = (int)(Math.random()*4);
        getRandomColor = getColor().toString();
    }

    public Color1 getColor()
    {
       return colors[a2];
    }
________________________________________________________________________

        //inner class  
      class LeftClicked implements ActionListener
      {
          public void actionPerformed(ActionEvent e)
           {
               if(getRandomColor == "red")
               {
                   centerPanel.setBackground(Color.red);
               }
               else if (getRandomColor == "blue")
               {
                   centerPanel.setBackground(Color.blue);
               }
               else if (getRandomColor == "green")
               {
                   centerPanel.setBackground(Color.green);
               }
               else
               {
                   centerPanel.setBackground(Color.yellow);
               }
               setA2();
         }
        }

________________________________________________________________________

//basic enums class to represent the constant colors.

    public enum Color1
   {
    red, green, blue, yellow;
   }

大家干杯!

【讨论】:

    【解决方案2】:

    在我看来,这是在乞求一个索引从 0 到 3 的数组 Color[4] - 而不是将您的随机 int 更改为字符串或整数键并进行哈希查找。


    完全假的类,展示了如何将数组与随机数一起使用

    public class foo
    {
        private Color[] colors = { Color.red, Color.green, Color.blue, Color.yellow };
    
        public Color getColor()
        {
            return colors[getRandom(0, 3)];
        }
    
        private int getRandom(int min, int max)
        {
            return 2;
        }
    
        enum Color {
            red, green, blue, yellow;
        }
    }
    

    【讨论】:

    • 嗨,是的,这就是我最初所做的,但是如何从数组集合中返回一个随机值。我尝试生成一个随机数,将其分配给一个 int 变量,然后将该变量与数组的索引值进行比较,但我没有找到如何返回存储数组值的索引 int 值的运气!
    • 感谢您的编辑,就像一个魅力..!感谢大家的意见。
    【解决方案3】:

    您需要一种将字符串转换为实际颜色的方法。我会使用这样的东西:

    public static Color stringToColor(final String value) {
        if (value == null) {
          return Color.black;
        }
        try {
          // get color by hex or octal value
          return Color.decode(value);
        } catch (NumberFormatException nfe) {
          // if we can't decode lets try to get it by name
          try {
            // try to get a color by name using reflection
            final Field f = Color.class.getField(value);
    
            return (Color) f.get(null);
          } catch (Exception ce) {
            // if we can't get any color return black
            return Color.black;
          }
        }
      }
    

    (来自 2D-Graphics/Convertsagivenstringintoacolor.htm">http://www.java2s.com/Tutorial/Java/0261_2D-Graphics/Convertsagivenstringintoacolor.htm)

    【讨论】:

      【解决方案4】:

      改用数组:

      String[] colors = new String[]{"white", "red"... etc};
      int random = random.nextInt(colors.length);
      
      String randomColor = colors[random];
      

      编辑:如果您愿意,可以用字符串替换您的 Color 类(或基元)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-03-15
        • 2012-09-05
        • 2023-03-08
        • 1970-01-01
        • 1970-01-01
        • 2021-02-06
        • 2021-01-10
        相关资源
        最近更新 更多