在Java中查找两个数组元素的索引级和
在Java中,数组是一个对象。它是一种非原始数据类型,用于存储相同数据类型的值。
根据问题陈述,我们必须找到两个不同数组的索引级和,并将其存储到第三个数组中。假设 a1[] 是第一个数组,a2[] 是第二个数组,a3[] 是第三个数组,则 a1[] 和 a2[] 的和应存储在 a3[] 中,即
a1[0] + a2[0] = a3[0] a1[1] + a2[1] = a3[1] a1[2] + a2[2] = a3[2] and so on.
让我们开始吧!
注意 - 两个数组的长度必须相同,并且数组元素必须是数字。
在本文中,您将看到如何使用Java编程语言查找两个数组元素相对于其索引位置的和,并将它们存储到另一个数组中。
让我们开始。
向您展示一些实例
实例-1
Suppose a1[] array is {5, 6, 3, 2, 4, 11} and a2[] array is {3, 9, 5, 21, 19, 2}
添加两个数组后,结果将为 -
Resultant array is: [8, 15, 8, 23, 23, 13]
实例-2
Suppose a1[] array is {9, 6, 1, 2, 41, 21} and a2[] array is {3, 9, 8, 31, 9, 42}
添加两个数组后,结果将为 -
Resultant array is: [12, 15, 9, 33, 50, 63]
实例-3
Suppose a1[] array is {51, 16, 33, 2, 14, 21} and a2[] array is {3, 9, 8, 31, 9, 42}
添加两个数组后,结果将为 -
Resultant array is: [84, 25, 89, 23, 53, 42]
算法
步骤 1 - 声明并初始化一个整数数组。
步骤 2 - 检查两个数组的长度是否相等。
步骤 3 - 如果两个数组的长度相等,则使用“a1[] + a2[] = a3[]”将它们相加。
步骤 4 - 打印结果数组
步骤 5 - 否则打印“两个数组的长度应该相同”。
语法
要获取数组的长度(该数组中的元素数量),数组有一个内置属性,即length。
下面指的是它的语法 -
array.length
其中,'array' 指的是数组引用。
多种方法
我们提供了不同方法的解决方案。
通过使用数组的静态初始化。
通过使用用户定义的方法。
让我们逐一查看程序及其输出。
方法-1:通过使用数组的静态初始化
示例
在这种方法中,数组元素将在程序中初始化。然后根据算法找到两个数组元素相对于索引的和,并将其存储到另一个数组中。
import java.util.*;
public class Main {
//main method
public static void main(String[] args){
//Declare and initialize the array elements
int[] a = {51, 16, 33, 2, 14, 21};
int[] b = {33, 9, 56, 21, 39, 21};
//get length of an array and store it in c array
int[] c = new int[a.length];
//check if length of both array are equal
if(a.length==b.length){
//logic implementation
for (int i = 0 ,j=0,k=0; i < a.length; i++,j++,k++){
c[k] = a[i] + b[j];
}
//Print the result
System.out.println("Resultant array is:");
System.out.println(Arrays.toString(c));
} else {
System.out.println("Length of both array should be same");
}
}
}
输出
Resultant array is: [84, 25, 89, 23, 53, 42]
方法-2:通过使用用户定义的方法
示例
在这种方法中,数组元素将在程序中初始化。然后通过将数组作为参数传递来调用用户定义的方法,并在方法内部根据算法找到两个数组元素相对于索引的和,并将其存储到另一个数组中。
import java.util.*;
public class Main{
//main method
public static void main(String[] args){
//Declare and initialize the array elements
int[] a = {9, 6, 1, 2, 41, 21};
int[] b = {3, 9, 8, 31, 9, 42};
//calling user defined method
add(a, b);
}
//user defined method
public static void add(int []a, int []b){
//get length of an array and store it in c array
int[] c = new int[a.length];
//check if length of both array are equal
if(a.length==b.length){
//logic implementation
for (int i = 0 ,j=0,k=0; i < a.length; i++,j++,k++){
c[k] = a[i] + b[j];
}
//Print the result
System.out.println("Resultant array is:");
System.out.println(Arrays.toString(c));
} else {
System.out.println("Length of both array should be same");
}
}
}
输出
Resultant array is: [12, 15, 9, 33, 50, 63]
在本文中,我们探讨了如何使用Java编程语言查找两个数组元素相对于其索引的和,并将值存储到另一个数组中。
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP