- I don't remember what this was for, but here it is!
1 public class FillWithSevens {
2 public static void main(String[] args) {
3 int[] x = new int[3];
4
5 for (int i=0; i<3; i++) {
6 x[i] = 7;
7 }
8 }
9 }
- Modifying an array:
1 class ModifyArray {
2 public static void main(String[] args) {
3 int[] x = { 1, 1 };
4 int[] y = x;
5
6 y[0] = 3;
7
8 System.out.println(x[0]);
9 }
10 }
3
- Reverse an array in a new array:
1 public class ReverseNewArray {
2 public static void main(String[] args) {
3 int[] x = { 1, 2, 3 };
4
5 int[] y = new int[x.length];
6
7 int len = x.length;
8 int j = 0;
9 for (int i=len-1; i>=0; i--) {
10 y[j] = x[i];
11 System.out.println(java.util.Arrays.toString(y));
12 j++;
13 }
14 System.out.println(java.util.Arrays.toString(x));
15 }
16 }
[3, 0, 0]
[3, 2, 0]
[3, 2, 1]
[1, 2, 3]
- Reverse an array in place:
1 public class ReverseInPlace {
2 public static void main(String[] args) {
3 int[] x = { 1, 2, 3, 4, 5, 6, 7, 8 };
4
5 int j = x.length-1;
6 for (int i=0; i<x.length/2; i++) {
7 int f = x[i];
8 x[i] = x[j];
9 x[j] = f;
10 System.out.println(java.util.Arrays.toString(x));
11 j--;
12 }
13 }
14 }
[8, 2, 3, 4, 5, 6, 7, 1]
[8, 7, 3, 4, 5, 6, 2, 1]
[8, 7, 6, 4, 5, 3, 2, 1]
[8, 7, 6, 5, 4, 3, 2, 1]
No comments:
Post a Comment