Home > Java > javaTutorial > body text

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

WBOY
Release: 2023-05-16 09:22:05
forward
910 people have browsed it

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));
    }
Copy after login

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));
    }
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template