码迷,mamicode.com
首页 > 其他好文 > 详细

Array Basics

时间:2020-06-03 00:32:38      阅读:55      评论:0      收藏:0      [点我收藏+]

标签:size   spec   last   average   java   dex   item   extra   elements   

Java Program to Find Largest Element of an array

In this program, you‘ll learn to find the largest element in an array using a for loop in Java.

Example: Find largest element in an array

package com.programiz;

public class Largest {

    public static void main(String[] args) {
        double[] numArray = { 23.4, -34.5, 50.0, 33.5, 55.5, 43.7, 5.7, -66.5 };
        double largest = numArray[0];

        for (double num : numArray) {
            if(largest < num)
                largest = num;
        }

        System.out.format("Largest element = %.2f", largest);
    }
}

When you run the program, the output will be:

Largest element = 55.50

In the above program, we store the first element of the array in the variable largest.

Then, largest is used to compare other elements in the array. If any number is greater than largest, largest is assigned the number.

In this way, the largest number is stored in largest when it is printed.

Java Program to Calculate Average Using Arrays

In this program, you‘ll learn to calculate the average of the given arrays in Java.

Example: Program to Calculate Average Using Arrays

package com.programiz;

public class Average {

    public static void main(String[] args) {
        double[] numArray = { 45.3, 67.5, -45.6, 20.34, 33.0, 45.6 };
        double sum = 0.0;

        for (double num: numArray) {
           sum += num;
        }

        double average = sum / numArray.length;
        System.out.format("The average is: %.2f", average);
    }
}

When you run the program, the output will be:

The average is: 27.69

In the above program, the numArray stores the floating point values whose average is to be found.

Then, to calculate the average, we need to first calculate the sum of all elements in the array. This is done using a for-each loop in Java.

Finally, we calculate the average by the formula:

average = sum of numbers / total count

In this case, the total count is given by numArray.length.

Finally, we print the average using format() function so that we limit the decimal points to only 2 using "%.2f"

Java Program to Print an Array

In this program, you‘ll learn different techniques to print the elements of a given array in Java.

Example 1: Print an Array using For loop

package com.programiz;

public class Array {
    
    public static void main(String[] args) {
        int[] array = { 1, 2, 3, 4, 5 };
        
        for (int element : array) {
            System.out.println(element);
        }
    }
}

When you run the program, the output will be:

1
2
3
4
5

In the above program, the for-each loop is used to iterate over the given array, array.

It accesses each element in the array and prints using println().

Example 2: Print an Array using standard library Arrays

package com.programiz;

import java.util.Arrays;

public class Array {
    
    public static void main(String[] args) {
        int[] array = { 1, 2, 3, 4, 5 };
        
        System.out.println(Arrays.toString(array));
    }
}

When you run the program, the output will be:

[1, 2, 3, 4, 5]

In the above program, the for loop has been replaced by single line of code using Arrays.toString() function.

As you can see, this gives a clean output without any extra lines of code.

Example 3: Print a Multi-dimenstional Array

package com.programiz;

import java.util.Arrays;

public class Array {
    
    public static void main(String[] args) {
        int[][] array = {{1, 2}, {3, 4}, {5, 6, 7}};
        
        System.out.println(Arrays.deepToString(array));
    }
}

When you run the program, the output will be:

[[1, 2], [3, 4], [5, 6, 7]]

In the above program, since each element in array contains another array, just using Arrays.toString() prints the address of the elements (nested array).

在上面的程序中,由于数组中的每个元素都包含另一个数组,因此仅使用Arrays.toString()即可打印元素的地址(嵌套数组)

To get the numbers from the inner array, we just another function Arrays.deepToString(). This gets us the numbers 1, 2 and so on, we are looking for.

为了从内部数组中获取数字,我们只需要另一个函数Arrays.deepToString()。这使我们得到数字1、2,依此类推,寻找所有数字

This function works for 3-dimensional arrays as well.

Example 4: 使用数组进行进制转换-1

package com.programiz;

public class Array {
    
    public static void main(String[] args) {
        DecimalToHex(60);
    }
    
    public static void DecimalToHex(int number) {
        for (int i = 0; i < 8; i++) {
            int temp = number & 15;
            
            if (temp > 9) 
                System.out.print((char)(temp - 10 + ‘A‘));
            else 
                System.out.print(temp);
            number = number >>> 4;
        }
        
        /*
        int n1 = number & 15;
        System.out.println("n1 = " + n1);
        
        number = number >>> 4;
        int n2 = number & 15;
        System.out.println("n2 = " + n2);
        */
    }
}
// C3000000

Example 5: 查表法

package com.programiz;

public class Array {
    
    public static void main(String[] args) {
        DecimalToHex(60);
    }
    
    public static void DecimalToHex(int number) {
       
        char chs = { ‘0‘, ‘1‘, ‘2‘, ‘3‘,
                     ‘4‘, ‘5‘, ‘6‘, ‘7‘, 
                     ‘8‘, ‘9‘, ‘A‘, ‘B‘,
                     ‘C‘, ‘D‘, ‘E‘, ‘F‘ };
        
        for (int i = 0; i < 8; i++) {
            int temp = number & 15;
            
            System.out.print(chs[temp]);
            
            number = number >>> 4;
        }
    }  
}
// c3000000

Example 6: 指针

package com.programiz;

public class Array {
    
    public static void main(String[] args) {
        DecimalToHex(60);
    }
    
    public static void DecimalToHex(int number) {
       
        char chs = { ‘0‘, ‘1‘, ‘2‘, ‘3‘,
                     ‘4‘, ‘5‘, ‘6‘, ‘7‘, 
                     ‘8‘, ‘9‘, ‘A‘, ‘B‘,
                     ‘C‘, ‘D‘, ‘E‘, ‘F‘ };
        
        char[] arr = new char[8];
        
        int pos = 0;
        
        while (number != 0) {
            int temp = number & 15;
           	arr[pos++] = chs[temp];
            number = number >>> 4;
        }
        
        System.out.println("pos = " + pos);
        
        for (int i = 0; i < pos; i++) {
            System.out.print(arr[i]);
        }
    }
}
// C3

Example 7: 优化

package com.programiz;

public class Array {
    
    public static void main(String[] args) {
        DecimalToHex(60);
    }
    
    public static void DecimalToHex(int number) {
        char chs = { ‘0‘, ‘1‘, ‘2‘, ‘3‘,
                     ‘4‘, ‘5‘, ‘6‘, ‘7‘, 
                     ‘8‘, ‘9‘, ‘A‘, ‘B‘,
                     ‘C‘, ‘D‘, ‘E‘, ‘F‘ };
        
        char[] arr = new char[8];
        int pos = arr.length;
        
        while (num != 0) {
            int temp = number & 15;
            arr[--pos] = chs[temp];
            number = number >>> 4;
        }
        
        System.out.println("pos = " + pos);
        for (int i = pos; i < arr.length; i++) {
            System.out.print(arr[i]);
        }
    }
}
// 3C

Java Array: Exercises, Practice, Solution Section01

Java Array Exercises [74 exercises with solution]

1. Write a Java program to sort a numeric array and a string array

package com.w3resource;

import java.util.Arrays;

public class ArraySortExample {

    public static void main(String[] args) {

        int[] my_array1 = {1789, 2035, 1899, 1456, 2013};
        String[] my_array2 = {"Java", "Python", "PHP", "C#", "C Programming", "C++"};

        System.out.println("Original numeric array : " + Arrays.toString(my_array1));
        Arrays.sort(my_array1);
        System.out.println("Sorted numeric array : " + Arrays.toString(my_array1));

        System.out.println("Original string array : " + Arrays.toString(my_array2));
        Arrays.sort(my_array2);
        System.out.println("Sorted string array : " + Arrays.toString(my_array2));
    }
}

Output

Original numeric array : [1789, 2035, 1899, 1456, 2013]
Sorted numeric array : [1456, 1789, 1899, 2013, 2035]
Original string array : [Java, Python, PHP, C#, C Programming, C++]
Sorted string array : [C Programming, C#, C++, Java, PHP, Python]

2. Write a Java program to sum values of an array.

package com.w3resource;

public class SumValues {
    
    public static void main(String[] args) {
        int my_array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
		int sum = 0;
        
        for (int i : my_array) {
            sum += i;
        }
        
        System.out.println("The sum is " + sum);
    }
}

Output

The sum is 55

3. Write a Java program to print the following grid.

// Print the specified grid
package com.w3resource;

public class SpecifiedGrid {
    
    public static void main(String[] args) {
        
        int[][] arr = new int[5][7];
        
        for (int i = 0; i < 5; i++) {
            for (int j = 0; j < 7; j++) {
                System.out.printf("%2d", arr[i][j]);
            }
            System.out.println();
        }
    }
}

Output

 0 0 0 0 0 0 0
 0 0 0 0 0 0 0
 0 0 0 0 0 0 0
 0 0 0 0 0 0 0
 0 0 0 0 0 0 0

4. Write a Java program to calculate the average value of array elements.

package com.w3resource;

public class CalculateAverage {
    
    public static void main(String[] args) {
        
        int[] numbers = new int[]{20, 30, 25, 35, -16, 60, -100};
        
        // calculate sum of all array elements
        int sum = 0;
        for (int i = 0; i < numbers.length; i++) {
            sum += numbers[i];
        }
        
        // calculate average value
        double average = sum / numbers.length;
        System.out.println("Average value of the array elements is: " + average);
    }
}

Output

Average value of the array elements is: 7.0 

5. Write a Java program to test if an array contains a specific value.

package com.w3resource;
    
public class SpecificValue {

    public static boolean contains(int[] arr, int item) {
        for (int n : arr) {
            if (item == n) {
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        int[] my_array = {1789, 2035, 1899, 1456, 2020};

        System.out.println(contains(my_array, 2020));
        System.out.println(contains(my_array, 2036));
    }
}

Output

true
false

6. Write a Java program to find the index of an array element.

package com.w3resource;

public class FindArrayIndex {

    public static int findIndex(int[] my_array, int num) {
        if (my_array == null)
            return -1;

        int len = my_array.length;
        int i = 0;
        while (i < len) {
            if (my_array[i] == num) {
                return i;
            } else {
                i += 1;
            }
        }

        return -1;
    }

    public static void main(String[] args) {

        int[] my_array = {25, 14, 56, 15, 36, 56, 77, 18, 29, 49};

        System.out.println("Index position of 25 is: " + findIndex(my_array, 25));
        System.out.println("Index position of 77 is: " + findIndex(my_array, 77));
    }
}

Output

Index position of 25 is: 0
Index position of 77 is: 6

7. Write a Java program to remove a specific element from an array.

package com.w3resource;

import java.util.Arrays;

public class RemoveSpecificElement {

    public static void main(String[] args) {

        int[] my_array = {25, 14, 56, 15, 36, 56, 77, 18, 29, 49};

        System.out.println("Original Array: " + Arrays.toString(my_array));

        // Remove the second element (index->1, value->14) of the array
        int removeIndex = 1;

        for (int i = removeIndex; i < my_array.length - 1; i++) {
            my_array[i] = my_array[i + 1];
        }

        // We cannot alter the size of an array, after the removal,
        // the last and second last element in the array will exist twice
        System.out.println("After removing the second element: " + Arrays.toString(my_array));
    }
}

Output

Original Array: [25, 14, 56, 15, 36, 56, 77, 18, 29, 49]
After removing the second element: [25, 56, 15, 36, 56, 77, 18, 29, 49, 49]

8. Write a Java program to copy an array by iterating the array.

package com.w3resource;

import java.util.Arrays;

public class CopyArrayByIterating {

    public static void main(String[] args) {
        int[] my_array = {25, 14, 56, 15, 36, 56, 77, 18, 29, 49};
        int[] new_array = new int[10];

        System.out.println("Source Array: " + Arrays.toString(my_array));

        for (int i = 0; i < my_array.length; i++) {
            new_array[i]=my_array[i];
        }

        System.out.println("New Array: " + Arrays.toString(new_array));
    }
}

Output

Source Array: [25, 14, 56, 15, 36, 56, 77, 18, 29, 49]
New Array: [25, 14, 56, 15, 36, 56, 77, 18, 29, 49]

9. Write a Java program to insert an element (specific position) into an array.

package com.w3resource;

import java.util.Arrays;

public class InsertElement {

    public static void main(String[] args) {

        int[] my_array = {25, 14, 56, 15, 36, 56, 77, 18, 29, 49};

        // Insert an element in 3rd position of the array (index->2, value->5)

        int Index_position = 2;
        int newValue = 5;

        System.out.println("Original Array: " + Arrays.toString(my_array));

        for (int i = my_array.length - 1; i > Index_position; i--) {
            my_array[i] = my_array[i - 1];
        }
        my_array[Index_position] = newValue;
        System.out.println("New Array: " + Arrays.toString(my_array));
    }
}

Output

Original Array: [25, 14, 56, 15, 36, 56, 77, 18, 29, 49]
New Array: [25, 14, 5, 56, 15, 36, 56, 77, 18, 29]

10. Write a Java program to find the maximum and minimum value of an array.

package com.w3resource;

import java.util.Arrays; 

public class FindValue {
    static int max;
  	static int min;

    public static void max_min(int my_array[]) {
    
        max = my_array[0];
        min = my_array[0];
        int len = my_array.length;
        for (int i = 1; i < len - 1; i = i + 2) {
            if (i + 1 > len) {
                if (my_array[i] > max) 
                    max = my_array[i];
                if (my_array[i] < min) 
                    min = my_array[i];
            }
            if (my_array[i] > my_array[i + 1]) {
                if (my_array[i] > max) 
                    max = my_array[i];
                if (my_array[i + 1] < min) 
                    min = my_array[i + 1];
            }
            if (my_array[i] < my_array[i + 1]) {
                if (my_array[i] < min) 
                    min = my_array[i];
                if (my_array[i + 1] > max) 
                    max = my_array[i + 1];
            }
        }
    }

    public static void main(String[] args) {
        
        int[] my_array = {25, 14, 56, 15, 36, 56, 77, 18, 29, 49};
        max_min(my_array);
        System.out.println(" Original Array: "+Arrays.toString(my_array));
        System.out.println(" Maximum value for the above array = " + max);
        System.out.println(" Minimum value for the above array = " + min);
    }
}

Output

Original Array: [25, 14, 56, 15, 36, 56, 77, 18, 29, 49]                       
Maximum value for the above array = 77                                         
Minimum value for the above array = 14

Array Basics

标签:size   spec   last   average   java   dex   item   extra   elements   

原文地址:https://www.cnblogs.com/PrimerPlus/p/13034770.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!