java implement array expansion, insertion, shrinkage and array element search. (Accessibly)

Catalogue

Preface : 

Expansion : 

        Preface : 

        Mentality : 

        Code Demonstration : 

Insertion : 

        Requirement : 

        Mentality : 

        Code Demonstration : 

Shrinkage : 

        Mentality : 

        Code Demonstration : 

Element Search : 

        Requirement : 

        Mentality : 

        Code Domenstration : 


Preface : 

        Hello, guys. This blog we will share how to implement array expansion, shrinkage and array element search in java. There would be three main chapter in this blog, and every chapter will be subdivided into many parts, such as requirement, mentality, code demonstration, etc. Let's start!

Expansion : 

        Preface : 

        To be honest, it's a little bit complicated to expand or shrink an array in java. Because java doesn't offer any methods to expand or shrink an array straightway. The length of an array is always fix from it is created. So, we can't achieve out requirements directly. We can finish it by transferring the point. Yeah, you guess right. Make a new array to take the place of the old array

        Mentality : 

        1.To start with, we need to creat an array, supposed name it as "arr", whatever. Then we input the number which we wanna add to the array. Use a variable to save it. 

        2.Acquiescently, we add the wantNum to the end of the array. Create another new array which is one longer than the original array. We can use for-loop to assign the valuse of original array to new array. Then put the wantNum into the new array. That's OK~

        3.Finally, we can add a judge structure and a do-while loop to expand array infinitely.

        Code Demonstration : 

package csdn.array;

import java.util.Scanner;

public class ArrayAdd {
    public static void main (String[] args) {
        int[] arr = {5, 11, 23, 211, 985, 5};

        System.out.println("=====The original array is:=====");
        for (int i = 0; i < arr.length; ++i) {
            System.out.print(arr[i] + "\t");
        }
        System.out.println();

        do {
            System.out.println("Input the number which you wanna add to the array:");
            Scanner sc = new Scanner(System.in);
            int wantNum = sc.nextInt();
            sc.nextLine();
			/*
				Δ Remember what this line of code "sc.nextLine()" does:
					It digests the content after the blank character to make sure
				that next "nextLine" function will correctly receive the content which you
				literally want to input.

				Δ But why we need this line of code?
					Because the nextInt() function will cut your input content according to the
				blank character like Tab key, space key, or carriage return key automatically and
				pass them on. And the nextLine() function use line feed key as its separator.
					So, if you use nextInt() function and nextLine() function at a same
				time, and unfortunately, the nextInt() function is the former, you need to be cautious.
				We can't neglect a truth that the effect would be one carriage return key and one line
				feed key when we press the "Enter" key in Windows system.
			*/

            int[] arrNew = new int[arr.length + 1];

            for (int i = 0,j = 0; i < arr.length; ++i,++j) {
                arrNew[j] = arr[i];
            }
            arrNew[arr.length] = wantNum;
            arr = arrNew;	//Key procedure : Change arr's point.

            System.out.println("=====The expended array is:=====");
            for (int i = 0; i < arr.length; ++i) {
                System.out.print(arr[i] + "\t");
            }
			/*
				//System.out.print(arr[i] + "\t");  Notice this line of code:
				If here use '', It will be considered as AscII,
				So use "" here.
				"+" is key. Don't forget the usage of "+".
			*/

            System.out.println("\nIf you wanna add again,please input \"Yes\", or the program will exit:");
            String trigger = sc.nextLine();

            if ("Yes".equals(trigger)) {
                continue;
            } else {
                sc.close();
                break;
            }
        } while (true);
    }
}

        Operation Effect : 

 

Insertion : 

        Requirement : 

        If you thought last chapter is just so so,  here is a more difficult challenge. Now you need to prepare an ascending array, and then insert a element into the array, but what's different now is that you need to keep array in ascending order after insertion operation.              

        Mentality : 

        1.Firstly, we just need to carry out two preparations :  get an ascending array and input the number which will be inserted into. Assign values to this array in ascending order, we can achieve it by using for-loop.

        2.Make sure that where you should insert the number. We can add a judgement step in a for-loop. Finding the element which is greater than or equal to the number while traversing the array. If we find it, assign this element's index to a variable to save it.

        3.Create a new array, then assign the old array's elements to the new array. Naturally, we use for-loop to make it. Supposed we use variable i to represent the new array's index and variable j to represent the old array's index, but carefully,  we need to ensure variable j skip the loop once. Because the new array's length is one longer than the old one, when we find the index thich we will insert the number into, we need to assign the number to this index's element of the new array, which make we have to do this.

        Code Demonstration : 

package csdn.array;

import java.util.Scanner;

public class ArrayInsert {
    public static void main(String[] args) {
        //preparation:
        //1>
        Scanner sc = new Scanner(System.in);
        System.out.println("Please input the length of array which you want:");
        int len = sc.nextInt();
        int[] array = new int[len];

        System.out.println("Please assign values to this int array in ascending order:");
        array[0] = sc.nextInt();
		/*
			Firstly, we assign a value to the first element of the array here.
			Otherwise, we have no element to compare. Because the value of the
			first element of the array is a random trash value.
		*/

        label1 :
        for (int i = 1; i < array.length; ++i) {

            if ((array[i] = sc.nextInt()) >= array[i-1]) {
                continue;
            } else {
                System.out.println("ERROR! Please input in ascending order:");
                i--;
                continue label1;
            }
        }

        System.out.println("==============array before expansion:==============");
        for (int i = 0; i < array.length; ++i) {

            System.out.print(array[i] + " ");
        }
        System.out.println();

        //2>
        System.out.println("Input the element you want to add:");
        int addition = sc.nextInt();

        //1) locating
        int index = -1;
        for (int i = 0; i < array.length; ++i) {

            if (addition <= array[i]) {

                index = i;
                break;
            }
        }
        if (index == -1) {

            index = array.length; 	//if not, insert at the end of array.
        }

        //2) insertion
        int[] arrayNew = new int[array.length + 1];
        //Keep an eye on it, a method of making j less recurrent than i.
        for (int i = 0,j = 0; i < arrayNew.length; ++i) {

            if (index == i) {
                arrayNew[i] = addition;
                continue;
            } else {
                arrayNew[i] = array[j];
                j++;
            }
        }
        array = arrayNew;//Change the point
        //3) output
        System.out.println("==============array after expansion:==============");
        for (int i = 0; i < array.length; ++i) {
            System.out.print(array[i] + " ");
        }

        sc.close();
    }
}

        Operation Effect :         

 

Shrinkage : 

        Shrink an array is in a similar way. So if you could understand how to expand an array, this chapter is just a piece of cake.

        Mentality : 

        1.Prepare an array.

        2.Acquiescently, we subtract the last element from the array. Likewise, use for-loop. But more  easily, we just need to create a new array which is one shorter than the original array. Then assign the elements of the old array to the new one.

        3.Finally, don't forget to change the array's point.And similarly, we can also use a do-while loop to subtract the element from the array over and over again, but when the length of array is just one, we need to hint that there is no element to subtract from.

        Code Demonstration : 

package csdn.array;

import java.util.Scanner;

public class ArraySubtract {
    public static void main (String[] args) {
        int[] arr = {1, 2, 3, 4, 6, 7, 8, 131, 4635, 998};
        System.out.println("=====The original array is :=====");
        for (int i = 0; i < arr.length; ++i) {
            System.out.print(arr[i] + "\t");
        }
        System.out.println();
        System.out.println("Now we will subtract the last element from array arr:\n");

        do {
            Scanner sc = new Scanner(System.in);
            //int poorNum = sc.nextInt();
            //sc.nextLine();

            int[] arrNew = new int[arr.length - 1];

            for (int i = 0,j = 0; i < arr.length-1; ++i,++j) {
                arrNew[j] = arr[i];
            }
            //arrNew[arra.length] = poorNum;
            arr = arrNew;						//Key prodedure : Change arra's point.

            System.out.println("=====The subtracted array is :=====");
            for (int i = 0; i < arr.length; ++i) {
                System.out.print(arr[i] + "\t");
            }
			/*
				If here use '', It's will be considered as AscII,
				So use "" here.
			*/

            System.out.println("\nIf you wanna subtract again,please input \"Yes\", or the program will exit:");
            String trigger = sc.nextLine();
            if ("Yes".equals(trigger)) {
                continue;
            } else {
                sc.close();
                break;
            }
        } while (arr.length > 1);
        if (arr.length == 1) {
            System.out.println("No elements can be subtracted from arra!Yeah, the number of elements must > 0,you know.");
        } else {
            System.out.println("exit,Thanks");
        }
    }
}

        Operation effect : 

 

Element Search : 

        This chapter is also easy to understand. And its quantity of code is the fewest.So, let's start!

        Requirement : 

        You can create an arbitrary type array, supposed String type, whatever, and then input the element whch you want to search, if programme find it, print its index in array. If doesn't, print "Can't find it".

        Mentality : 

        1.Initialize the array, input something you want, whatever.

        2.Comparing the input element which you want to search with the element of the array while traversing the array by for-loop

        3.Give user the hint according to search results.

        Code Domenstration : 

package csdn.array;

import java.util.Scanner;

public class ElementSearch {
    public static void main (String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Please input the element which you wanna search:");

        String name = sc.nextLine();
        String[] nameBase = {"King", "Lrving", "Cyan", "Five", "Ice"};
        int index = -1;


        for (int i = 0; i < nameBase.length; ++i) {
            if (name.equals(nameBase[i])) {
                System.out.println("Yeah,you find it!");
                System.out.println("And its index in array is " + i);
                index = i;
                break;
            }
        }

        if (index == -1) {
            System.out.println("Can't find it!");
        }

        sc.close();
    }
}

        Operation effect : 

System.out.println("END------------------------------------------------------------------------------"); 

  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Cyan_RA9

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值