循环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 楼答案
不能执行
qwerty['W']
,因为qwerty
不是数组,Java只允许对实际数组进行数组索引。没有Java等价于Python的__getitem__
方法,所以不能让其他类支持类似数组的访问。您需要编写一个普通方法来执行查找至于可变参数(
String... rows
),这只是传递数组的一种奇特方式。当调用Keyboard
构造函数时,可以在括号中写入多个字符串,它们将自动生成一个数组。在Keyboard
构造函数的实现中,它与参数为String[] rows
的情况相同目前还不完全清楚
Keyboard
构造函数应该做什么,但是如果您的目标是能够查找字母键的坐标,最简单的方法是在类中有一个Map
字段:然后,在构造函数中,可以为每个字母填充条目:
查找字母位置的函数只能从数组中获取条目:
而不是
qwerty['W']
,你要写qwerty.getPosition('W')