jhedmendoza
jhedmendoza

Reputation: 1399

Passing array to a method (Java)

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.

Upvotes: 0

Views: 15641

Answers (3)

Alpesh Prajapati
Alpesh Prajapati

Reputation: 1643

  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(3,"alpesh",names);
}

   public static void replaceArrayElement(int index, String replacename, String names[]){


       if(index<names.length){

           names[index] = replacename;

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

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

Upvotes: 0

Pramod Kumar
Pramod Kumar

Reputation: 8014

Declare replaceArrayElement as follows -

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

and call it as -

replaceArrayElement(2, "Einstein2", names);

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1499800

Well it's not clear where you'd get the values to pass in from, but here's how you would declare the method:

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

You'd call it with:

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

Note that I've used String[] name instead of String name[] - while the latter syntax is permitted, it's strongly discouraged as a matter of style.

Upvotes: 5

Related Questions