Java Sample Collection (iii)

Source: Internet
Author: User

Example 1. Filtration of the circulating body

 

 Public classCyclefilter { Public Static voidMain (string[] args) {//TODO auto-generated Method StubString[] Array=NewString[] {"White Eagle", "Red-crowned Crane", "Egret", "Parrot", "Oriole", "Eagle", "Crow", "Magpie", "Eagle",                "Cuckoo", "Eagle", "Sparrow", "Eagle", "Lark"};//Create an arraySYSTEM.OUT.PRINTLN ("There are a lot of birds in my garden, but recently there are a few eagles, please help me to take it.") "); intEaglecount=0;  for(String Str:array) {//foreach traversal array            if(Str.equals ("Eagle")) {//If you encounter an eagleSystem.out.println ("Found an eagle, had been put into a cage.") "); Eaglecount++; Continue;//Interrupt Loop} System.out.println ("Search for birds, found:" +str);//Otherwise, the output array element} System.out.println ("Catch it altogether:" +eaglecount+ "Eagle"); }}

The results of the implementation are as follows:

There are a lot of birds in my garden, but recently there are a few eagles, please help me to take it. Search birds, found: White Eagle search birds, found: red-crowned cranes search for birds, found: egrets search birds, found: Parrot Search birds, found: Oriole found an eagle, has been installed in the cage. Search birds, found: Crow search birds, found: Magpie found an eagle, has been installed in the cage. Search for birds, found: Cuckoo found an eagle, has been installed in the cage. Search for birds, found: Sparrow found an eagle, has been installed in the cage. Search birds, found: The Lark caught altogether: 4 Eagles

Example 2. Use the For loop to output a hollow diamond

Output Hollow diamond pattern, in a number of occasions encountered a similar case, this example with the use of nested for loop, the example is as follows:

 Public classDiamdemo { Public Static voidMain (string[] args) {//TODO auto-generated Method StubPrintrhomebus (10); }     Public Static voidPrintrhomebus (intsize) {        if(Size% 2==0) {size++;//Calculate Diamond Size        }         for(inti=0;i<size/2+1;i++) {             for(intj=size/2+1;j>i+1;j--) {System.out.print ("  ");//white space at the top left corner of the output            }             for(intj=0;j<2*i+1;j++) {                if(j==0| | j==2*i) {System.out.print ("*");//top half edge of output diamond}Else{System.out.print ("  "); }} System.out.println ("  "); }         for(inti=size/2+1;i<size;i++) {             for(intj=0;j<i-size/2;j++) {System.out.print ("  ");//output diamond lower left corner blank            }             for(intj=0;j<2*size-1-2*i;j++) {                if(j==0| | j==2* (size-i-1) {System.out.print ("*");//output diamond lower half edge}Else{System.out.print ("  "); }} System.out.println ("  "); }    }}

The execution results are as follows (the size of the empty string determines the width of the diamond, on the example two spacebar):

          *          *  *        *      *      *          *    *              *  *                  *    *              *      *          *        *      *          *  *            *  

Example 3. Use for loop output Yang Hui triangle

Yang Hui triangles are arranged by numbers, which can be regarded as a number table, the basic characteristic of which is that both sides are 1, the value of other positions is the sum of the values above and above the upper left corner. The sample code is as follows:

 Public classYhtriangle { Public Static voidMain (String args[]) {inttriangle[][]=New int[12] [];//Create a two-dimensional array and determine the length of one dimension         for(inti=0;i<triangle.length;i++) {//traversing the first layer of a two-dimensional arraytriangle[i]=New int[I+1];//Initialize the size of the second-level array             for(intj=0;j<=triangle[i].length-1;j++) {//traversing a second-level array                if(i==0| | j==0| | J==TRIANGLE[I].LENGTH-1) {//assigns an array element on both sides to a value of 1Triangle[i][j]=1; }Else{//other values are calculated byTriangle[i][j]=triangle[i-1][j]+triangle[i-1][j-1]; } System.out.print (Triangle[i][j]+ "\ T");//Output array elements} System.out.println (); }    }}

The execution results are:

1    1    1    1    2    1    1    3    3    1    1    4    6    4    1    1    5    5    1    1    6    , 6 1 1 7, 35    7    1    1 8 8    1    1    9    126    126    9    1    1    252    1    1    165-    462    462    165    1

Example 4. Numerical

4.1. Legal declaration values and initialization examples

intArr[];//declaring an array of type intString[] STR;//declaring an array of type stringint[] arr=New int[]{3,6,7,10,22};//declaring numeric values and initializing themintarr2={2,3,5,8};intmonth[]=New int[12];//declaring values and allocating memoryintMyarr[][];//declaring a two-dimensional array of type intMyarr=New int[3] [6];//allocates the same memory for each dimension of a two-dimensional array//allocate memory separately for each dimensionMyarr=New int[3][];myarr[0]=New int[3];myarr[1]=New int[4];myarr[2]=New int[5];intMYARR2[][]={{10,12},{20,22}};//initialize a two-dimensional array

4.2. Finding the sum of the elements of a one-dimensional array

Each element of a one-dimensional array has its own value, and the value of each element of the array is added and summed using a for loop based on the subscript of the array. Examples are as follows:

 Public classSumnum { Public Static voidMain (string[] args) {//TODO auto-generated Method Stub        int[] num= {12,13,22,33,35,36};//Create and initialize a one-dimensional array num        intsum=0;//sum of the variables summed and assigned an initial value of 0         for(inti=0;i<6;i++) {//iterating through the array with A for loop            if(i==5) {//determines whether the subscript of an array is 5System.out.print (num[i]+ "=");//The subscript of the array element is 5, the output equals sign}Else{System.out.print (Num[i]+"+");//otherwise the output plus sign} sum=sum+num[i];//to accumulate and sum up} System.out.println (sum); //Output and    }}

Execution of the result is: 12+13+22+33+35+36=151

4.3. Examples of regular two-dimensional arrays

For an integer array, the system automatically assigns a value of 0 to each element in the array after the creation is successful.

 Public classMatrix { Public Static voidMain (string[] args) {//TODO auto-generated Method StubSYSTEM.OUT.PRINTLN ("******* outputs a 3 row and 5 columns and all elements are 0 moment chen *******"); inta[][]=New int[3] [5];//defines a two-dimensional array, with each element being 0 by default         for(inti=0;i<a.length;i++) {             for(intj=0;j<a[i].length;j++) {//iterate through each element in the arraySystem.out.print (a[i][j]+ "");            } System.out.println (); //Output Spaces} System.out.println ("******* element *******" in a two-dimensional array with output initialization); intb[][]= {{11,12,13,14},                {21,22,23,24},                {31,32,33,34}};  for(inti=0;i<b.length;i++) {             for(intj=0;j<b[i].length;j++) {System.out.print (B[i][j]+ "\ T");        } System.out.println (); }    }}

The execution results are:

Output a 3 row 5 column and all elements are 0 moments Chen *******0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ******* output initializes the elements in the two-dimensional array *******11    21< c6/>22    34    

4.4. Three-dimensional arrays

The declaration of a three-dimensional array is similar to a one-dimensional, two-dimensional array, initialized with a 3-layer brace when initializing a three-dimensional array. Examples are as follows:

 Public classThirdarr { Public Static voidMain (string[] args) {//TODO auto-generated Method Stub        intarr[][][]=New int[][][] {            {{10,20,30},{40,50,60}},            {{11,21,31},{41,51,61}},            {{12,22,32},{42,52,62}}        }; //Create a three-dimensional array         for(inti=0;i<arr.length;i++) {//iterating through an arraySystem.out.println ("the" + (i+1) + "Elements of a three-dimensional array is a" +arr[0].length+ "dimension, as follows:");  for(intj=0;j<arr[0].length;j++) {//iterating through an array                 for(intk=0;k<arr[0][0].length;k++) {System.out.print (Arr[i][j][k]+ "\ T");            } System.out.println (); }        }    }}

The execution results are:

the 1th element of a three-dimensional array is a 2-dimensional array, as follows:        The 2nd element of the three-dimensional array is a 2-dimensional arraywith the following contents: 11        The 3rd element of the three-dimensional array is a 2-dimensional array, which reads as follows:    62    

Java Sample Collection (iii)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.