Summary of arrays in Java (classroom summary)

Source: Internet
Author: User
Tags sin

Features of the array:

Arrays (Array)
A simple data structure
element has the same data type
Once created, the dimensions remain the same
Elements are continuously distributed in memory
Example one: examples by reference and by value
Source:

passarray.java//passing arrays and individual array elements to Methodspublic class Passarray {public static void main (string[] args) {int a[] = {1, 2, 3, 4, 5}; String output = "The values of the original array are:\n"; for (int i = 0; i < a.length; i++) output + = "   " + A[i];ou Tput + = "\n\neffects of passing Array" + "element call-by-value:\n" + "A[3" before Modifyelement: "+ a[3];modifyelement (A [3]); O  Utput + = "\na[3" after Modifyelement: "+ a[3];output + =" \ n Effects of passing entire array by reference "; Modifyarray (a); Array a passed call-by-referenceoutput + = "\n\nthe values of the modified array are:\n"; for (int i = 0; i < A.lengt H i++) Output + = "   " + a[i]; SYSTEM.OUT.PRINTLN (output);} public static void Modifyarray (Int. b[]) {for (int j = 0; J < B.length, J + +) B[j] *= 2;} public static void modifyelement (int e) {e *= 2;}}

Output Result:

Analysis:

The biggest key to passing the array type method parameters by reference and by value is:
When using the former, if there is code in the method that changes the value of the array element, the original array element is actually modified directly.
Using the latter does not have the problem, and the method body modifies only one copy of the original array element.
Example two: Assigning values between arrays:

Source:

public class Arrayinram {public static void main (string[] args) {//define and initialize the array, use static initialization int[] A = {5, 7, 20}; System.out.println ("an element in an array:");//loop output a array of elements for (int i = 0; i < a.length; i++) {System.out.print (A[i] + ",");} Defines and initializes array B, using dynamic initialization int[] B = new int[4];//The length of the output B array System.out.println ("The initial length of the \NB array is:" + b.length);//Because A is a int[] type, B is also an int [] Type, so you can assign the value of a to B. That is, let the B reference point to the array B = A referred to by a reference; System.out.println ("B=a, after assignment, the element of B array is:");//loop output B array of elements for (int i = 0; i < b.length; i++) {System.out.print (B[i] + ",");} Output the length of the B array again System.out.println ("\ n assignment, the length of the B array is:" + B.length);}}

Experimental results:

Analysis:

The b=a in the code means that the array A is assigned to B, then the length of the output B is equal to the length of a.

Example three: Drawing Gobang disk with two-dimensional arrays and circular statements

Source:

Import java.io.*;p Ublic class qipan{//define a two-dimensional array to act as the chessboard private string[][] board;//define the size of the checkerboard private static int board_size = 15;  public void Initboard () {//Initialize checkerboard array BOARD = new string[board_size][board_size];//assigns each element "╋" to draw the checkerboard for (int i = 0; i <) in the console Board_size; i++) {for (int j = 0; J < Board_size; J + +) {Board[i][j] = "╋";}} Method of output checkerboard on console public void Printboard () {//print each array element for (int i = 0; i < board_size; i++) {for (int j = 0; J < board_s IZE; J + +) {//print array elements without wrapping System.out.print (Board[i][j]);}    Outputs a newline character System.out.print ("\ n") after each line of array elements is printed;} public static void Main (string[] args) throws Exception {Qipan GB = new Qipan (); Gb.initboard (); Gb.printboard (); /This is the method used to get the keyboard input BufferedReader br = new BufferedReader (new InputStreamReader (system.in));                String inputstr = null; System.out.println ("Please enter the coordinates of your chess, should be in X, y format:");//br.readline (): Whenever you enter a line on the keyboard press ENTER, the content you just entered will be read by BR. while ((Inputstr = Br.readline ()) = null) {//the string entered by the user is delimited by a comma (,) as a delimiter, separated into 2 strings string[] Posstrarr = Inputstr.split (",");//Convert 2 strings to the coordinates of the user playing chess int xPos = Integer.parseint (posstrarr[0]); int yPos = Integer.parseint (posstrarr[1]);//assign the corresponding array element as " ". GB.BOARD[XPOS-1][YPOS-1] = "";/* the computer randomly generates 2 integers, which are assigned to the board array as the coordinates of the computer chess. Also involved 1. The validity of the coordinates can only be a number, not beyond the Checkerboard Range 2. If the point of the chess, can not repeat chess. 3. After each chess game, you need to scan who won the */gb.printboard ();    System.out.println ("Please enter the coordinates of your chess should be in X, y format:");} }}

Experimental results:

Example four: converting integers to kanji reading strings (e.g. "1123" to "1123")

Source:

Package Hanzidufa;public class Num2rmb{private string[] Hanarr = {"0", "one", "two", "three", "four", "five", "six", "seven", "Eight", "IX "};p rivate string[] Unitarr = {" Ten "," Hundred "," thousand "," Million "," 100,000 "," Million "};/** * Convert a four-bit numeric string into a kanji String * @param numstr need to be converted four-bit numeric string * @r The Eturn four-bit numeric string is converted into a character string.  */private string Tohanstr (String numstr) {string result = ""; int numlen = Numstr.length ();//Loop through the numeric string for each digit for (int i = 0; i < Numlen; i++) {//convert char numbers to int numbers, because their ASCII values are exactly the same 48//so subtract the char number by 48 to get the int number, for example ' 4 ' is converted to 4. int num = Numstr.charat (i)-48;//if it is not the last digit and the number is not 0, you need to add units (thousand, Hundred, ten) if (i! = numLen-1 && num! = 0) {result + = Han Arr[num] + unitarr[numlen-2-i];} Otherwise, do not add units else{//if the previous number is "0" and not "0" when adding if (Result.length () >0 && hanarr[num].equals ("0") && Result.charat (Result.length ()-1) = = ' 0 ') Continue;result + = Hanarr[num];}} Only single digit, return directly if (Result.length () ==1) return Result;int index=result.length () -1;while (Result.charat (index) = = ' 0 ') { index--;} if (Index!=result.length ()-1) return result.substring (0,inDEX+1); else {return result;}} public static void Main (string[] args) {NUM2RMB nr = new NUM2RMB (); System.out.println ("Integer only (0~ million)");//test turns a four-bit numeric string into a character string System.out.println (Nr.tohanstr ("0")); System.out.println (Nr.tohanstr ("1")); System.out.println (Nr.tohanstr ("10")); System.out.println (Nr.tohanstr ("15")); System.out.println (Nr.tohanstr ("110")); System.out.println (Nr.tohanstr ("123")); System.out.println (Nr.tohanstr ("105")); System.out.println (Nr.tohanstr ("1000")); System.out.println (Nr.tohanstr ("1100")); System.out.println (Nr.tohanstr ("1110")); System.out.println (Nr.tohanstr ("1005")); System.out.println (Nr.tohanstr ("1105")); System.out.println (Nr.tohanstr ("1111")); System.out.println (Nr.tohanstr ("10000")); System.out.println (Nr.tohanstr ("10001")); System.out.println (Nr.tohanstr ("10011")); System.out.println (Nr.tohanstr ("10111")); System.out.println (Nr.tohanstr ("11111")); System.out.println (Nr.tohanstr ("11000")); System.out.println (Nr.tohanstr ("11100")); System.out.println (Nr.tohanstr ("11110")); System.out.println (Nr.tohanstr ("101110"));    System.out.println (Nr.tohanstr ("1001110")); }}

Experimental results:

Example five: Representing the amount "Chinese character expression method"

Source:

Package Hanzidufa;public class Num2rmb{private string[] Hanarr = {"0", "one", "II", "three", "Restaurant", "WU", "Lu", "Qi", "ba", "JIU "};p rivate string[] Unitarr = {" Min "," angle "," meta "," ten "," Hundred "," thousand "," Million "," 100,000 "," Million "};/** * turn a four-bit numeric string into a kanji String * @param numstr The four-bit numeric string that needs to be converted * @return a four-bit numeric string to be converted into a Chinese character string. */string tohanstr (String numstr) {string result = ""; int numlen = Numstr.length (); int flag;flag=numstr.indexof ('. '); String numstr1,numstr2;numstr1=numstr.substring (0,flag); numstr2=numstr.substring (flag+1,numlen); int numLen1= Numlen-flag;int numlen2=2;//sequentially iterates through each digit of the numeric string for (int i = 0; i < numLen1; i++) {//converts char numbers to int numbers because their ASCII values are exactly 48 So the char number minus 48 gets the int type number, for example ' 4 ' is converted to 4. int num = Numstr1.charat (i)-48;//if it is not the last digit and the number is not 0, you need to add units (thousand, Hundred, ten) result + = Hanarr[num] + unitarr[numlen-2-i];} Only single digit, directly return for (int j=0;j<2;j++) {int Num1=numstr2.charat (j) -48;result + = Hanarr[num1] + unitarr[1-j];}    return result;} public static void Main (string[] args) {NUM2RMB nr = new NUM2RMB (); System.out.println ("Only Integer (0~ million)" is supported;//test turns a four-bit numeric string into a Chinese character string System.out.println (Nr.tohanstr ("123.11")); }}

Experimental results:

Example six: Using arrays to store large numbers and implement factorial operations

Source:

    Import Java.util.Scanner;                 public class Bignumberjiecheng {private static int[] Resultarray = new int[10000000];          static int resultjinwei = 0;                    Static long index = 0;              public static void Main (string[] args) {System.out.println ("Please enter the value of n that requires factorial:");              Scanner sin = new Scanner (system.in);              int number = Sin.nextint ();              Long Maxindex = method (number);              System.out.println ("factorial is:");                  for (Long i = maxIndex-1; I >= 0; i--) {System.out.print (resultarray[(int) i]);                  if (i% 100 = = 0) {//The output format is processed here because the Eclipse compiler's console outputs a limit of the length of each line, so it is processed to output 100 numbers per line System.out.println (); }}} public static Long method (long number) {Long Maxinde              x = 1;              int temp = 0;              int tempmaxindex = 0;              Resultarray[0] = 1; For (LonG i = 1; I <= number;                      i++) {for (Long j = 0; J < Maxindex; J + +) {resultarray[(int) j] *= I;                      resultarray[(int) j] + = Resultjinwei;                      temp = resultarray[(int) j];                          if (temp >=) {resultarray[(int) index] = temp% 10;                          Resultjinwei = TEMP/10;                          index++;                                                if (maxindex<index+1) Maxindex = index+1;                          } else {index++;                      Resultjinwei = 0;                                }} index = 0;          } return Maxindex;   }                }

Experiment:

Example seven: randomly generate 10 numbers (1~10), output array contents, and output the array's and.

Source:

Package Sjs;public class SJSJ {public static void main (string[] args) {//TODO auto-generated method stubint a[]=new int [ 10];int sum=0;for (int i=0;i<10;i++) {a[i]=1+ (int) (Math.random () *10); sum+=a[i];} for (int j=0;j<10;j++) {System.out.println (a[j]);} System.out.print ("The sum of the array is:" +sum);}}

Experimental results:

Summary of arrays in Java (classroom summary)

Related Article

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.