I have a program that accepts a number that represents an array index and a
String to replace the array element corresponding to the index.
Here is my code:
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!");
}
}
What I need to do is to put the int index variable and String value variable inside the method replaceArrayElement as a parameters. But I don’t know how to call a method with different data type parameters. Can somebody show me how?? Thank you.
Well it’s not clear where you’d get the values to pass in from, but here’s how you would declare the method:
You’d call it with:
Note that I’ve used
String[] nameinstead ofString name[]– while the latter syntax is permitted, it’s strongly discouraged as a matter of style.