day05作业-----------Java方法和数组

1. 定义方法完成,打印 nxn乘法表(n的取值范围是[1-9])

2. 给定一个排序数组,返回移除相同元素后数组的新长度。

答案:

1.

 1 import java.util.Scanner;
 2 // 定义方法完成,打印 nxn乘法表(n的取值范围是[1-9])
 3 public class Demo1 {
 4     public static void main(String[] args) {
 5         System.out.println("请输入一个0到9范围内的整数:");
 6         Scanner sc = new Scanner(System.in);
 7         int input = sc.nextInt();
 8         print(input);
 9         sc.close();
10     }

2.

 1 package com.day005;
 2 //给定一个排序数组,返回移除相同元素后数组的新长度。
 3 
 4 //注意:是一个排序数组。
 5 public class Demo2 {
 6         
 7         //声明一个排序数组
 8         int[] b = {1,1,2,3,4,4,5,5,5,8};
 9         int len = b.length;
10         for(int i = 1; i< b.length; i++) {
11             if(b[i-1] == b[i]) {
12                 len--;
13             }
14         }
15         System.out.println("原来长度为"+ b.length);
16         System.out.println("移除相同元素后数组的新长度为:"+ len);
17 
18     }
19 
20 }

 或

public class Demo {

    public static void main(String[] args) {
        int[] a = {1,2,5,4,8,5,4,7,2,1};
        int length = removeD(a);
        System.out.println(length);
    }


          public static int removeD(int[] a) {
            int i = 0;
            for(int j = 1; j < a.length; j++) {
                if(a[i] != a[j]) {
                    i++;
                    a[i] = a[j];
                }
            }
            return i+1;
          }

}

 

posted @ 2020-04-15 14:23  dust--  阅读(142)  评论(0编辑  收藏  举报