// My code is doing something; difficult to get.. still a concept can be grasped.
//I am having my method (searchCity) in class graph. this method is called from main
//class and is yes... selecting one array by charachter it is passed with
public class graph {
int a = 1000;
int flag = 0;
//array of all cities having elements as connection to other cities
public graph(){
char [] i = {'i','v'};
char [] v = {'v','u'};
char [] u = {'u','b','h'};
char [] b = {'b','p','f','u'};
char [] h = {'h','u','e'};
char [] e = {'e','h'};
char [] p = {'p','b','r','c'};
char [] c = {'c','p'};
char [] r = {'r','s','p'};
char [] s = {'s','f','r'};
char [] f = {'f','s','b'};
}
public void searchCity( char i, char j){
// check for equal array as parameter i (include must )
for (int z = 0 ; z < i.length; z ++) {
if (i[z] == 'j') {
int ascii = (int) 'j';
int flag = 1;
System.out.println(ascii);
}
else {
// checking for smallest cost in the complete array
int ascii = (int) i[z];
if(a>ascii)
a=ascii;
else continue;
}
}
if (flag==0){
char b = (char) a;
char [] c = {'b'};
}
searchCity(c, j);
}
我有一个类,其中有许多以字母命名的数组,如 char [] a、char [] b 等。我在类中还有一个方法。 在主类中,我创建了一个对象,如果我需要传递两个字母,这将类似于仅调用那些传递名称的数组的引用。 就像我在主类中的代码行如下: 对象.函数(char1, char2); 这些字符将是字母表(a,b,c等)可以做到吗?如何 ??请帮忙。我搜索了它,但确切的问题没有得到解答。问候
最佳答案
如果您询问如何将字符数组传递给函数,您所需要做的就是按如下方式设置函数:
public static void MyFunction(char[] a, char[] b) {
//do stuff to char arrays
}
然后,当您调用该函数时,您将能够将它们传递给:
char[] a = {'a', 'b', 'c'};
char[] b = {'d', 'e', 'f'};
MyObject.MyFunction(a, b);
如果您发布当前的代码,那将会很有帮助,这样我就可以准确地告诉您您想要做什么。
编辑:
如果您希望能够使用字符调用数组,我建议将它们包含在 HashMap 中:
Map<Character, Character[]> graph = new HashMap<Character, Character[]>();
graph.put('i', new Character[] {'i', 'v'});
graph.put('v', new Character[] {'v', 'u'});
graph.put('u', new Character[] {'u', 'b', 'h'});
// etc.
然后您可以按如下方式调用数组:
System.out.println(graph.get('i')[0]); // Prints 'i'
System.out.println(graph.get('i')[1]); // Prints 'v'
System.out.println(graph.get('i').length); // Prints '2'
所以函数可能是这样的:
public static void MyFunction(char a, char b) {
graph.get(a)[0]; // grab first character in array
for (int i=0; i<graph.get(b).length; i++) {
// recursively go through array with graph.get(b)[i]
}
}
希望这有帮助。
关于java - 将数组名称作为类方法中的参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28905902/