Reputation: 57
public static void main(String args[]) {
System.out.println("enter numbers: ");
Scanner input = new Scanner(System.in);
int nums[] = new int[9];
int noChange[] = new int[9];
for (int n = 0; n < 9; n++) {
nums[n] = input.nextInt();
n++;
}
noChange = nums;
getNextPermutation(nums);
while (hasNextPermutation(nums) == true) {
getNexpermutation(nums);...
}
Reverse(nums);
else {
while (!Arrays.equals(nums, noChange)) {
getNextPermutation(nums)
}
}
public static void getNextPermutation(int nums[]) {
int j = nums.length - 2;
while (nums[j] > nums[j + 1]) {
j--;
}
int k = nums.length - 1;
while (nums[j] > nums[k]) {
k--;
}
int temp = nums[j];
nums[j] = nums[k];
nums[k] = temp;
int r = nums.length - 1;
int s = j + 1;
while (r > s) {
int temp2 = nums[s];
nums[s] = nums[r];
nums[r] = temp2;
s++;
r--;
}
}
}
Some code that is not important to this question are omitted and I marked where the problem is. So I was trying to store input value into a new array, I was thinking that the value would not changed. However, when I test the code there, the result presented changed value to me. Such that I cannot compare "nums" and " nochange"...I am stuck on the store input into another place and never changed. What I am thinking is, when I want to use it, such as compare to changeable nums, I can grab it and do comparison. However, the input value does changed. I just wandering how to keep a input value separately and don't change?
Upvotes: 0
Views: 82
Reputation: 16498
Example to copy an array:
int[] src = new int[]{1,2,3,4,5};
int[] dest = new int[5];
System.arraycopy( src, 0, dest, 0, src.length );
so you have to change this line:
noChange = nums;
to
System.arraycopy( nums, 0, noChange , 0, nums.length );
Upvotes: 0
Reputation: 234815
Arrays are reference types in Java.
In writing noChange = nums
you are changing what noChange
refers to: it now refers to same array as nums
. (The previous array that noChange
was referring to is now eligible for garbage collection!)
So you can change that array either by manipulating it through nums
or by manipulating it through noChange
. In your code you are changing the array through nums
.
You probably want to deep copy the array. Do that using noChange = nums.clone();
Upvotes: 1