根据问题陈述,我们必须互相更改两个数组元素。换句话说,改变两个数组元素也可以称为交换或交换两个元素
让我们探索一下这篇文章,看看如何使用 java 编程语言来完成它。
向您展示一些实例实例1假设我们有以下数组 = [10, 2, 3, -5, 99, 12, 0, -1]
现在如果我们交换第 5 个和第 8 个元素,
然后,我们得到了新数组 [10, 2, 3, -5, -1, 12, 0, 99]
实例2假设我们有以下数组 = [55, 10, 29, 74, 12, 45, 6, 5, 269]
现在如果我们交换第四个和第八个元素
然后,我们得到了新数组 [55, 10, 29, 5, 12, 45, 6, 74, 269]
实例3假设我们有以下数组 = [556, 10, 259, 874, 123, 453, -96, -54, -2369]
现在如果我们交换第二个和第六个元素
然后,我们得到了新数组 [556, 453, 259, 874, 123, 10, -96, -54, -2369]
算法算法 1(通过使用第三个变量)第 1 步 - 存储数组后,取两个索引来交换元素。
第 2 步 - 将第一个元素存储在临时变量中。
第 3 步 - 现在将第二个元素值存储在第一个元素中
第 4 步 - 最后将临时变量值存储在第二个元素中。
第 5 步 - 打印数组元素。
算法2(不使用第三个变量)第 1 步 - 存储数组后,取两个索引来交换元素。
第 2 步 - 添加第一个和第二个元素,然后将它们存储在第一个元素中。
步骤 3 - 从第一个元素中减去第二个元素并将其存储在第二个元素中。
步骤 4 - 再次从第一个元素中减去第二个元素并存储在第一个元素中。
第 5 步 - 打印数组元素。
语法要获取数组的长度(该数组中的元素数量),数组有一个内置属性,即 length。
下面是它的语法 -
array.length
其中,“array”指的是数组引用。
您可以使用arrays.sort()方法对数组进行升序排序。
arrays.sort(array_name);
多种方法我们通过不同的方式提供了解决方案。
使用第三个变量更改两个数组元素。
在不使用第三个变量的情况下更改两个数组元素。
让我们一一看看该程序及其输出。
方法 1:使用第三个变量在这种方法中,我们通过使用另一个临时保存一个元素值的变量来更改数组元素。
示例import java.io.*;import java.util.arrays;public class main { public static void main(string[] args) { // the array elements int arr[] = { 10, 2, 3, -5, 99, 12, 0, -1 }; // print all array elements system.out.println(the array elements before swapping are-); for (int i : arr) { system.out.print(i + ); } // we will be swapping 2nd index element with 4th index element int firstindex = 2, secondindex = 4; // temp variable int temp = arr[firstindex]; // swapping arr[firstindex] = arr[secondindex]; arr[secondindex] = temp; // print all array elements system.out.println(\nthe array elements after swapping are-); for (int i : arr) { system.out.print(i + ); } }}
输出the array elements before swapping are-10 2 3 -5 99 12 0 -1 the array elements after swapping are-10 2 99 -5 3 12 0 -1
方法 2:不使用第三个变量在这种方法中,与之前的方法不同,我们无需使用其他变量即可更改数组元素。
示例import java.io.*;import java.util.arrays;public class main { public static void main(string[] args) { // the array elements int arr[] = { 10, 2, 3, -5, 99, 12, 0, -1 }; // print all array elements system.out.println(the array elements before swapping are-); for (int i : arr) { system.out.print(i + ); } // we will be swapping 2nd index element with 4th index element int firstindex = 2, secondindex = 4; // swapping array elements arr[firstindex] = arr[firstindex] + arr[secondindex]; arr[secondindex] = arr[firstindex] - arr[secondindex]; arr[firstindex] = arr[firstindex] - arr[secondindex]; // print all array elements system.out.println(\nthe array elements after swapping are-); for (int i : arr) { system.out.print(i + ); } }}
输出the array elements before swapping are-10 2 3 -5 99 12 0 -1 the array elements after swapping are-10 2 99 -5 3 12 0 -1
在本文中,我们探讨了如何使用 java 编程语言来更改两个数组元素。
以上就是如何在java中修改两个数组元素的详细内容。
