public class Swap_Numbers {
public static void main(String[] args) {
int numTens[] = {1, 2, 3, 4, 5}; // First array of numbers
int numHundred[] = {100, 200, 300, 400, 500}; //Second Array of Numbers
System.out.println (numTens[3]); // I want my numTens displays numHundred
System.out.println (numHundred[4]); // I want my numHundred displays numTens
}
}
我只是不知道我应该使用什么代码来交换 numTens 和 numHundred 的数据而不使用额外的变量..希望有人能解释我如何做谢谢!
最佳答案
I just don't know what codes should i use to swap the data of numTens and numHundred without using extra variables
基本上,您不应该这样做。只需采用临时变量的简单路线:
int[] tmp = numTens;
numTens = numHundred;
numHundred = tmp;
对于整数,您可以实际上使用没有临时变量的算术交换数组中的值(这与交换变量引用的数组不同),但是如果真的发现自己处于想要这样做的境地,那将是非常奇怪的。示例代码:
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
int[] x = { 1, 2, 3, 4, 5 };
int[] y = { 15, 60, 23, 10, 100 };
swapValues(x, y);
System.out.println("x: " + Arrays.toString(x));
System.out.println("y: " + Arrays.toString(y));
}
static void swapValues(int[] a, int[] b) {
// TODO: Validation
for (int i = 0; i < a.length; i++) {
a[i] += b[i];
b[i] = a[i] - b[i];
a[i] -= b[i];
}
}
}
即使在那里,我也会实际上使用一个临时变量来编写swapValues
,但是上面的代码只是为了证明一个观点...
关于java - 我如何交换数组的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18912388/