JAVA中数组总结(课堂总结)

数组的特点:

Arrays(数组)
一种简单的数据结构
元素具有相同的数据类型
一旦创建之后,尺寸保持不变
元素在内存中连续分布
例子一:按引用与按值传递的示例
源代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// PassArray.java
// Passing arrays and individual array elements to methods
 
public 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];
 
        output += "\n\nEffects of passing array " + "element call-by-value:\n"
                + "a[3] before modifyElement: " + a[3];
 
        modifyElement(a[3]);
 
        output += "\na[3] after modifyElement: " + a[3];
 
        output += "\n Effects of passing entire array by reference";
 
        modifyArray(a); // array a passed call-by-reference
 
        output += "\n\nThe values of the modified array are:\n";
 
        for (int i = 0; i < a.length; 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;
    }
 
}

 输出结果截图:

分析:

按引用传递与按值传送数组类型方法参数的最大关键在于:
使用前者时,如果方法中有代码更改了数组元素的值,实际上是直接修改了原始的数组元素。
使用后者则没有这个问题,方法体中修改的仅是原始数组元素的一个拷贝。
例子二:数组之间的赋值:

源代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class ArrayInRam {
    public static void main(String[] args) {
        // 定义并初始化数组,使用静态初始化
        int[] a = { 5, 7, 20 };
        System.out.println("a数组中的元素:");
        // 循环输出a数组的元素
        for (int i = 0; i < a.length; i++) {
            System.out.print(a[i] + ",");
        }
        // 定义并初始化数组b,使用动态初始化
        int[] b = new int[4];
        // 输出b数组的长度
        System.out.println("\nb数组的初始长度为:" + b.length);
        // 因为a是int[]类型,b也是int[]类型,所以可以将a的值赋给b。
        // 也就是让b引用指向a引用指向的数组
        b = a;
        System.out.println("b=a,赋值之后,b数组的元素为:");
        // 循环输出b数组的元素
        for (int i = 0; i < b.length; i++) {
            System.out.print(b[i] + ",");
        }
 
        // 再次输出b数组的长度
        System.out.println("\n赋值之后,b数组的长度为:" + b.length);
    }
}

 实验结果截图:

分析:

代码中b=a;表示将数组a赋值给b,则之后输出的b的长度就等于a的长度。

例子三:利用二维数组和循环语句绘制五子棋盘

源代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import java.io.*;
 
public class QiPan
{
    //定义一个二维数组来充当棋盘
    private String[][] board;
    //定义棋盘的大小
    private static int BOARD_SIZE = 15;
    public void initBoard()
    {
        //初始化棋盘数组
        board = new String[BOARD_SIZE][BOARD_SIZE];
        //把每个元素赋为"╋",用于在控制台画出棋盘
        for (int i = 0 ; i < BOARD_SIZE ; i++)
        {
            for ( int j = 0 ; j < BOARD_SIZE ; j++)
            {
                board[i][j] = "╋";
            }
        }
    }
    //在控制台输出棋盘的方法
    public void printBoard()
    {
        //打印每个数组元素
        for (int i = 0 ; i < BOARD_SIZE ; i++)
        {
            for ( int j = 0 ; j < BOARD_SIZE ; j++)
            {
                //打印数组元素后不换行
                System.out.print(board[i][j]);
            }
            //每打印完一行数组元素后输出一个换行符
            System.out.print("\n");
        }
    }
    public static void main(String[] args)throws Exception
    {
        QiPan gb = new QiPan();
        gb.initBoard();
        gb.printBoard();
        //这是用于获取键盘输入的方法
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String inputStr = null;
                System.out.println("请输入您下棋的座标,应以x,y的格式:");
        //br.readLine():每当在键盘上输入一行内容按回车,刚输入的内容将被br读取到。
        while ((inputStr = br.readLine()) != null)
        {
            //将用户输入的字符串以逗号(,)作为分隔符,分隔成2个字符串
            String[] posStrArr = inputStr.split(",");
            //将2个字符串转换成用户下棋的座标
            int xPos = Integer.parseInt(posStrArr[0]);
            int yPos = Integer.parseInt(posStrArr[1]);
            //把对应的数组元素赋为"●"。
            gb.board[xPos - 1][yPos - 1] = "●";            
            /*
             电脑随机生成2个整数,作为电脑下棋的座标,赋给board数组。
             还涉及
                1.座标的有效性,只能是数字,不能超出棋盘范围
                2.如果下的棋的点,不能重复下棋。
                3.每次下棋后,需要扫描谁赢了
             */
            gb.printBoard();
            System.out.println("请输入您下棋的座标,应以x,y的格式:");
        }
    }
}

 实验结果截图:

例子四:将整数转换为汉字读法字符串(比如“1123”转换为“一千一百二十三”)

 源代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package hanzidufa;
 
 
 
public class Num2Rmb
{
    private String[] hanArr = {"零" , "一" , "二" , "三" , "四" ,
        "五" , "六" , "七" , "八" , "九"};
    private String[] unitArr = {"十" , "百" , "千","万","十万","百万"};
 
     
 
    /**
     * 把一个四位的数字字符串变成汉字字符串
     * @param numStr 需要被转换的四位的数字字符串
     * @return 四位的数字字符串被转换成的汉字字符串。
     */
    private String toHanStr(String numStr)
    {
        String result = "";
        int numLen = numStr.length();
        //依次遍历数字字符串的每一位数字
        for (int i = 0 ; i < numLen ; i++ )
        {
            //把char型数字转换成的int型数字,因为它们的ASCII码值恰好相差48
            //因此把char型数字减去48得到int型数字,例如'4'被转换成4。
            int num = numStr.charAt(i) - 48;
            //如果不是最后一位数字,而且数字不是零,则需要添加单位(千、百、十)
            if ( i != numLen - 1 && num != 0)
            {
                result += hanArr[num] + unitArr[numLen - 2 - i];
            }
            //否则不要添加单位
            else
            {
                 
                //上一个数是否为“零”,不为“零”时就添加
                if(result.length()>0 && hanArr[num].equals("零") && result.charAt(result.length()-1)=='零')
                    continue;
                result += hanArr[num];
            }
        }
        //只有个位数,直接返回
        if(result.length()==1)
            return result;
         
        int index=result.length()-1;
        while(result.charAt(index)=='零'){
            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("只支持整数(0~百万)");
        //测试把一个四位的数字字符串变成汉字字符串
        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"));
         
    }
}

 实验结果截图:

例子五:将数字表示金额“汉字表达法”

源代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package hanzidufa;
 
public class Num2Rmb
{
    private String[] hanArr = {"零" , "壹" , "贰" , "叁" , "肆" ,
        "伍" , "陆" , "柒" , "捌" , "玖"};
    private String[] unitArr = {"分","角","元","十","百","千","万","十万","百万"};
 
     
 
    /**
     * 把一个四位的数字字符串变成汉字字符串
     * @param numStr 需要被转换的四位的数字字符串
     * @return 四位的数字字符串被转换成的汉字字符串。
     */
    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;
        //依次遍历数字字符串的每一位数字
        for (int i = 0 ; i < numLen1 ; i++ )
        {
            //把char型数字转换成的int型数字,因为它们的ASCII码值恰好相差48
            //因此把char型数字减去48得到int型数字,例如'4'被转换成4。
            int num = numStr1.charAt(i) - 48;
            //如果不是最后一位数字,而且数字不是零,则需要添加单位(千、百、十)
             
                result += hanArr[num] + unitArr[numLen - 2 - i];
        }
        //只有个位数,直接返回
        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("只支持整数(0~百万)");
        //测试把一个四位的数字字符串变成汉字字符串
        System.out.println(nr.toHanStr("123.11"));
         
         
    }
}

 实验结果截图:

例子六:利用数组储存大数字,并实现阶乘运算

源代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
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("请输入要求阶乘的N的值:"); 
        Scanner sin = new Scanner(System.in); 
        int number = sin.nextInt(); 
        long maxIndex = method(number); 
        System.out.println("阶乘为:"); 
        for (long i = maxIndex-1; i >= 0; i--) { 
            System.out.print(resultArray[(int) i]); 
            if(i % 100 == 0) { //此处对输出格式做处理时因为eclipse编译器的控制台每行输出的长度有限定,所以处理成每行输出100个数 
                System.out.println(); 
            
        
    
   
    public static long method(long number) { 
        long maxIndex = 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 >= 10) { 
                    resultArray[(int) index] = temp % 10
                    resultJinwei = temp / 10
                    index++; 
                    if(maxIndex<index+1
                        maxIndex = index+1
                       
                } else
                    index++; 
                    resultJinwei = 0
                }                
            
            index = 0
               
        
        return maxIndex; 
    
       

 实验截图:

例子七:随机生成10个数(1~10),输出数组内容,并输出数组的和。

源代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package sjs;
 
public class sjsj {
 
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int 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("数组之和为:"+sum);
     
    }
 
}

 实验结果截图:

 

posted @   Java民工陆小凤  阅读(1380)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
点击右上角即可分享
微信分享提示