Java,处理变量参数并引用基于它们创建的对象(?)

时间:2015-11-04 02:27:05

标签: java loops foreach

这将是我的第一个问题,我经常使用网站,但这是我第一次找不到答案。我尝试将一些在线发现的代码移植到java,最初用python编写,这是我第一次使用那些“花哨”循环并使用变量参数进行操作,所以我遇到了一些与这些主题相关的问题。
我也知道标题不好的问题,但我真的不知道如何标题。

我有一个这样的课程:

public class Keyboard {
Keyboard(String... rows){
    double y=0;
    for(String row : rows){
        double x=0;
        /** For-each loop is applicable for arrays and Iterable.  
           * String is not an array. It holds array of characters but it is not an array itself. 
            *String does not implement interface Iterable too.
            *If you want to use for-each loop for iteration over characters into the string you have to say:
            */
        for(char letter : row.toCharArray()){                
            if(letter!=' '){
                letter : new Point2D.Double(x,y);
                letter : System.out.println("Punkt " + letter + "   x: " + x + "   y: " + y);
                //to print it out like in python sauce, i guess I would have to overwrite tostring() 
            }
            x+=0.5;
        }  
        y++;
     }
}

然后像这样主要:

public class test {
public static void main(String[] args){
Keyboard qwerty = new Keyboard("Q W E R T Y U I O P",
                               " A S D F G H J K L ",
                               "   Z X C V B N M   ");
Point W = qwerty['W']; //this line is wrong
}

我知道键盘在这种情况下接受3个字符串作为参数,依此类推,但我不知道如何,嗯,从主要字母引用键盘中创建的特殊字母。

1 个答案:

答案 0 :(得分:1)

您无法执行qwerty['W']因为qwerty不是数组,Java只允许对实际数组进行数组索引。没有Java等同于Python的__getitem__方法,所以你不能让其他类支持类似数组的访问。你需要编写一个普通的方法来进行查找。

就可变参数(String... rows)而言,这只是传递数组的一种奇特方式。当您调用 Keyboard构造函数时,您可以在括号中写入多个字符串,它们将自动生成一个数组。在Keyboard构造函数的实现中,它与参数String[] rows相同。

Keyboard构造函数应该做什么并不完全清楚,但如果您的目标是能够查找字母键的坐标,那么最简单的方法就是使用{{1}类中的字段:

Map

然后,在构造函数中,您可以使用每个字母的条目填充它:

public class Keyboard {
  // ...
  private final Map<Character, Point> keyPositions = new HashMap<>();
  // ...
}

查找字母位置的功能只能从数组中获取条目:

for (char letter : row.toCharArray()) {
  // ...
  keyPositions.put(letter, new Point2D.Double(x, y));
  // ...
}

而不是public Point getPosition(char letter) { return keyPositions.get(letter); } 您要写qwerty['W']