gpt4 book ai didi

java - 将数组传递给方法 (Java)

转载 作者:行者123 更新时间:2023-12-01 17:30:57 25 4
gpt4 key购买 nike

我有一个程序,它接受一个代表数组索引的数字和一个用于替换索引对应的数组元素的字符串。

这是我的代码:

public static void main(String args[]){

String names[]={"Alvin", "Einstein", "Ace", "Vino", "Vince"};

for(int i=0; i<names.length;i++)
System.out.println(i + " - " + names[i]);

replaceArrayElement(names);
}

public static void replaceArrayElement(String name[]){

int index = 0;
String value = "";

Scanner scan = new Scanner(System.in);

System.out.print("\nEnter the index to be replaced:");
index = scan.nextInt();

if(index<name.length){

System.out.print("Enter the new value:");
value = scan.nextLine();

name[index] = scan.nextLine();

System.out.println("\nThe new elements of the array are");

for(int j=0; j<name.length;j++)
System.out.println(name[j]);
}
else{
System.out.println("Error!");
}
}

我需要做的是将int索引变量和String值变量作为参数放入replaceArrayElement方法中。但我不知道如何调用具有不同数据类型参数的方法。有人可以告诉我怎么做吗?谢谢。

最佳答案

目前尚不清楚从哪里获取要传入的值,但以下是声明该方法的方式:

public static void replaceArrayElement(String[] name, int index, String value)

你可以这样调用它:

// Get the values from elsewhere, obviously
replaceArrayElement(array, 5, "fred");

请注意,我使用了 String[] name 而不是 String name[] - 虽然后一种语法是允许的,但它是强烈的由于风格问题而不鼓励。

关于java - 将数组传递给方法 (Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11027645/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com