Home  >  Article  >  Java  >  How to write a method in java to multiply each element in an array by *2

How to write a method in java to multiply each element in an array by *2

WBOY
WBOYforward
2023-05-16 09:22:05827browse

Write a method to * 2 each element in the array

 /**
     * 在原来的数组上扩大2倍
     * @param array
     */
    public static void enlarge(int[] array){
        for (int i = 0; i <array.length ; i++) {
            array[i] = array[i]*2;
        }
 
    }
 
    public static void main(String[] args) {
        int[] array = {1,2,3,4,5,6,7};
        enlarge(array);
        System.out.println(Arrays.toString(array));
    }

Print the result:

How to write a method in java to multiply each element in an array by *2

Expand the original array by 2 times the value Put it in a new array

/**
     * 把原来数组扩大2倍的值放在一个新的数组中
     * @param array
     * @return
     */
    public static int[] func(int[] array) {
        int[] ret = new int[array.length];
        for (int i = 0; i < array.length; i++) {
            ret[i] = array[i] * 2;
        }
        return ret;
    }
 
    public static void main(String[] args) {
        int[] array = {1,2,3,4,5,6,7};
       int[] ret =  func(array);
        System.out.println(Arrays.toString(ret));
    }

The above is the detailed content of How to write a method in java to multiply each element in an array by *2. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete