Homework

Hack 1: Swap the first and last element in the array

public class ArrayMethods1 {
    private int[] values = {0,1,2,3,4,5,6,6,7};

void run(){
     System.out.println("Swap first and last element");
    for(int i = 0; i < values.length;i++){
        System.out.print(values[i]);
    }
    //swap code
    int temp = values[0];
    values[0] = values[values.length-1];
    values[values.length-1]=temp;

    System.out.println();
    for(int i = 0; i < values.length;i++){
        System.out.print(values[i]);
    }
}

    public static void main(String[] args) {
        ArrayMethods1 am = new ArrayMethods1();
        am.run();
        
    }
}

ArrayMethods1.main(null);
Swap first and last element
012345667
712345660

Hack 2: Replace all even elements with 0

public class ArrayMethods2 {
    private int[] values = {0,1,2,3,4,5,6,6,7};

    void run(){
        for(int i = 0; i < values.length;i++){
            System.out.print(values[i]);
        }
        for(int i = 0; i < values.length;i++){
            if(values[i]%2==0){
                values[i]=0;
            }
        } 
        System.out.println();
        for(int i = 0; i < values.length;i++){
            System.out.print(values[i]);
        }
    }

    public static void main(String[] args) {
        ArrayMethods2 am = new ArrayMethods2();
        am.run();
        
    }
}
ArrayMethods2.main(null);
012345667
010305007

Hack 3: Return true if the array is currently sorted in increasing order

public class ArrayMethods3 {
    static int[] valuesOne = {0,1,2,3,4,5,6,6,7};
    static int[] valuesTwo = {1,1,5,3,6,5,6,6,7};

    void run(int [] array1){
        for(int i = 0; i < array1.length;i++){
            System.out.print(array1[i]);
        }
        
        System.out.println("\nThe method returned "+test(array1));
    }

    boolean test(int [] array2){
        for(int i = 0; i < array2.length-1;i++){
            if(array2[i]<array2[i+1]){
                break;
            }else{
                return false;
            }
        } 
        return true;
    }

    public static void main(String[] args) {
        ArrayMethods3 am = new ArrayMethods3();
        am.run(valuesOne);
        am.run(valuesTwo);
        
    }
}
ArrayMethods3.main(null);
012345667
The method returned true
115365667
The method returned false