有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

这将是我在这里的第一个问题,我用了很多网站,但第一次我还没有找到答案。我尝试将一些在线找到的代码移植到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) 个答案

  1. # 1 楼答案

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

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

    目前还不完全清楚Keyboard构造函数应该做什么,但是如果您的目标是能够查找字母键的坐标,最简单的方法是在类中有一个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'],你要写qwerty.getPosition('W')