Arrays as parameters Adding values

Write a method named addValueByIndex.

The method should take an array of longs and add value to the specified element by its index.

Here is a description of the parameters:

  1. an array of longs;
  2. the index of an element (int);
  3. a value for adding (long).

The method must return nothing.

The following invocation should work correctly:

addValueByIndex(array, index, value);

Where array is an array of longs, index is an integer variable, value is a long value for adding.

Sample Input 1:

1 1 1 1 1
2 100

Sample Output 1:

1 1 101 1 1
import java.util.*;

public class Main {

    public static void addValueByIndex(long[] array, int index, long value) {
        array[index] += value;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        long[] array = Arrays.stream(scanner.nextLine().split(" "))
                .mapToLong(Long::parseLong)
                .toArray();
        int index = scanner.nextInt();
        long value = scanner.nextLong();
        addValueByIndex(array, index, value);
        Arrays.stream(array).forEach(e -> System.out.print(e + " "));
    }
}

All strings have a very powerful method split() that takes as an argument a regular expression which it uses to split the string in to an array of separate elements (the separator is not included in the elements). In this case the space character is used as a separator. The resulting array of strings is then passed to the class generic method Arrays.stream() which takes an array as input and turns it in to a Stream. The Streams mapToLong() method is then used to parse each element in to a long. The result of which is then converted back from a stream of long to an array of long using the streams toArray() method. I hope this helps.

posted @ 2020-08-12 09:54  longlong6296  阅读(165)  评论(0)    收藏  举报