Java

Java面试题

杨辉三角

  • 使用二维数组打印一个10 行杨辉三角
  • 【提示】
  • ①、第一行有一个元素,第n行有n个元素
  • ②、每一行的第一个元素和最后一个元素都是1
  • ③、从第三行开始,对于非第一个元素和最后一个元素的元素。即:yanghuii = yanghuii-1 + yanghuii-1;
package com.zuowey.exer;

public class YanghuiTest {
    public static void main(String[] args) {
        //1.声明并初始化二维数组
         int[][] yanghui = new int[10][];
        //2.给数组的元素赋值
         for (int i = 0; i < yanghui.length; i++) {
            yanghui[i] = new int[ i + 1 ];
            
            //2.1给首末元素赋值
            yanghui[i][0] = yanghui[i][i] = 1;
            
            //2.2给每行的非首末元素赋值
            if(i > 1) {
                for (int j = 1; j < yanghui[i].length - 1; j++) {
                    yanghui[i][j] = yanghui[i-1][j-1] + yanghui[i-1][j];
                }
            }
        }
        
        //3.遍历二维数组
         for (int i = 0; i < yanghui.length; i++) {
            for (int j = 0; j < yanghui[i].length; j++) {
                System.out.print(yanghui[i][j] + " ");
            }
            System.out.println();
        }
    }
}

定义长度6位int型数组

  • 创建一个长度为6的int型数组,要求数组元素的值都在1-30之间,且是随机赋值。同事,要求元素的值各不相同
package com.zuowey.exer;

public class ArrayExer2 {
    public static void main(String[] args) {
        int[] arr = new int[6];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = (int)(Math.random() * 30) + 1;
            
            for (int j = 0; j < i; j++) {
                if(arr[i] == arr[j]) {
                    i--;
                    break;
                }
            }
        }
        
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }
    }
}
微信扫一扫,向我赞赏

微信扫一扫,向我赞赏

微信扫一扫,向我赞赏

支付宝扫一扫,向我赞赏

This is just a placeholder img.