第六次课总结及思考

public class MultiplicationTable {

	//九九乘法表
	//v1.2
	public static void main(String[] args) {

		for (int i = 1; i <= 9; i++) {
			for (int j = 1; j <= i; j++) {
				if (j % i == 0) {
					System.out.print(j + " * " + i + " = " + (j * i) + "\n");
				}
				else
					System.out.print(j + " * " + i + " = " + (j * i) + ",");
			}
//			System.out.println();
		}
	}

}

public class IsoscelesTriangle {

	/**
	 * 等腰三角形
	 * @author cmz 
	 * @date 2016/06/03
	 * @version 1.0
	 * @param args
	 */
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		System.out.print("请输入腰长:");
		int num = input.nextInt();
		for (int i = 1; i <= num; i++) {
			for (int j = 1; j <= num - i; j++) {
				System.out.print(" ");
			}
			for (int j = 1; j <= i - 1; j++) {
				System.out.print("*");
			}
			for (int j = 1; j <= i; j++) {
				System.out.print("*");
			}
			System.out.println();
		}
	}

}
**
 * 数组去重
 * 
 * @author cmz
 * @date 2016/06/03
 * @version 1.0
 *
 */
public class StringArrayAbandonRepeat {

	public static void main(String[] args) {

		String[] str = { "Java", "C++", "Php", "C#", "Python", "C++", "Java" };
		// String [] str = {"13", "212", "13", "13", "13", "2", "1"};
		// String [] str = {"11", "22", "22", "44", "44", "23", "13"};
		// String [] str = {"111", "111", "22", "44", "44", "111", "111"};
		String[] strNew = AbandonRepeat(str);

		System.out.println("数组去重的结果:" + Arrays.toString(strNew));
	}

	/**
	 * @version v1.1
	 * @param str
	 * @return String[] dateTime 2016/05/30
	 */
	public static String[] AbandonRepeat(String[] str) {
		int numOfNull = 0;

		// 声明sreNew的长度为传人数组str的长度
		String[] strNew = new String[str.length];
		System.out.println("AbandonRepeat方法内->数组去重前->str = "
				+ Arrays.toString(str));

		// 两重for循环中,如果有两个元素相同,则把第一个元素置为空字符串,
		// 特殊地,对于有超过2个以上相同的元素,也可以保留1个
		for (int i = 0; i < str.length; i++) {
			for (int j = i; j < str.length; j++) {
				if (i == j) {
					continue;
				} else if (str[i].equals(str[j])) {
					str[i] = "";
				}
			}
		}

		System.out.println("AbandonRepeat方法内->中间状态->str = "
				+ Arrays.toString(str));

		// 忽略含有空字符串的元素,其他的元素赋值给数组strNew
		for (int k = 0, i = 0; i < str.length; i++) {
			if (str[i].equals(new String(""))) {
				// 计算有多少个空字符串,也用于计算strNew数组中有多少个null
				numOfNull++;
				continue;
			} else {
				strNew[k] = str[i];
				k++;
			}
		}

		System.out.println("AbandonRepeat方法内->去重后->strNew = "
				+ Arrays.toString(strNew));

		// 新数组strAbandonNull声明的长度为原数组的长度减去null的个数
		String[] strAbandonNull = new String[str.length - numOfNull];

		for (int i = 0; i < strAbandonNull.length; i++) {
			strAbandonNull[i] = strNew[i];
		}
		return strAbandonNull;
	}

}

/**
 * 数组去重,另一个版本
 * 
 * @author cmz
 * @date 2016/06/03
 * @version 1.1
 *
 */
public class StringArrayAbandonRepeat {

	public static void main(String[] args) {

		StringArrayAbandonRepeat saar = new StringArrayAbandonRepeat();

		String[] str = { "Java", "C++", "Php", "C#", "Python", "C++", "Java" };
		// String [] str = {"13", "212", "13", "13", "13", "2", "1"};
		// String [] str = {"11", "22", "22", "44", "44", "23", "13"};
		// String [] str = {"111", "111", "22", "44", "44", "111", "111"};

		String[] strResult = saar.AbandonRepeat(str);

		System.out.println("数组去重的结果:" + Arrays.toString(strResult));
	}

	/**
	 * @version v1.2
	 * @param str
	 * @dateTime 2016/06/03
	 */
	public String[] AbandonRepeat(String[] str) {
		//用于数组中空字符串的计数
		int numOfNull = 0;

		System.out.println("AbandonRepeat方法内->数组去重前->str = "
				+ Arrays.toString(str));

		// 两重for循环中,如果有两个或者两个以上的元素相同,则把除了第一个元素外的重复元素置为空字符串
		for (int i = 0; i < str.length; i++) {
			for (int j = 0; j < i; j++) {
				if (str[i].equals(str[j])) {
					str[i] = "";
					// 计算有多少个空字符串,用于计算strRemoveNull的长度
					numOfNull++;
					break;
				}
			}
		}

		System.out.println("AbandonRepeat方法内->中间状态->str = "
				+ Arrays.toString(str));
		// 声明数组strIncludeNull的长度 = 原数组str长度
		String[] strIncludeNull = new String[str.length];

		for (int i = 0, j = 0; i < strIncludeNull.length; i++) {
			// 忽略含有空字符串的元素,其他的元素赋值给数组strIncludeNull
			if (!str[i].equals(new String(""))) {
				strIncludeNull[j] = str[i];
				j++;
			}
		}

		// 数组strRemoveNull用于存储strIncludeNull中除了null之外的元素
		String[] strRemoveNull = new String[strIncludeNull.length - numOfNull];

		for (int i = 0; i < strRemoveNull.length; i++) {
			strRemoveNull[i] = strIncludeNull[i];
		}
		System.out.println("AbandonRepeat方法内->去重后->数组strRemoveNull = "
				+ Arrays.toString(strRemoveNull));
		return strRemoveNull;
	}

}


第六次课的总结及思考


一、运算符

        1、算术运算符:+   -   *   /   %   ++   --

              注意:(1)a++表示在a之后才++,所以在以下代码中:

                                   int a = 10;

                                   System.out.println("前a = " + a);
                                   System.out.println("a++ = " + (a++));
                                   System.out.println("后a = " + a);

                                       结果:前a = 10
                                                   a++ = 10
                                                   后a = 11


                            (2)--a表示在a之前已经--: 

                    int a = 10;
                    System.out.println("前a = " + a);
                    System.out.println("--a = " + (--a));
                    System.out.println("后a = " + a);

                                       结果:前a = 10
                                                   --a = 9
                                                   后a = 9

        2、关系运算符:>   <   ==   >=   <=   !=

        3、赋值运算符:+=  -=  *=  /=   %=

        4、逻辑运算符:&&   ||   !

        5、位运算符:

              (1)与(&):2个操作数中,对应的2个位都是1时,才返回1,否则返回0

              (2)或(|):2个操作数中,对应的2个位只要有1个是1,结果就是1

              (3)非(~):翻转包括符号位的每一位。如:

              int a = -5;
              System.out.println(a+"= " + Integer.toBinaryString(a));
              System.out.println("~a = " + Integer.toBinaryString((~a)));
                             结果:

                               -5= 11111111111111111111111111111011
                               ~a = 100

                        注意:负数在计算机中是以补码形式表示的,非运算就在补码的基础上进行

              (4)异或(^):2个操作数中,对应的2个位,如果不同,则结果为1;相同,结果为0。如:

              int a = 13;
              int b = 7;
              System.out.println(a+" = "+Integer.toBinaryString(a));
              System.out.println(b+" = "+Integer.toBinaryString(b));
              System.out.println("a ^ b = "+Integer.toBinaryString((a^b)));

                            结果:

                                  13 = 1101
                                   7 = 111
                                   a ^ b = 1010

             int a = -13;
             int b = 7;
             System.out.println(a+" = "+Integer.toBinaryString(a));
             System.out.println(b+" = "+Integer.toBinaryString(b));
             System.out.println("a ^ b = "+Integer.toBinaryString((a^b)));

                           结果:

                                -13 = 11111111111111111111111111110011
                                7 = 111
                                a ^ b = 11111111111111111111111111110100

              (5)左移(<< n):如ina a = 1; a = a << 1;即为a对应的二进制乘以2(左移,后面补0)

              (6)右移(>>):如ina a = 1; a = a >> 1;即为a对应的二进制除以2(右移,前面补符号位)

              (7)无符号位右移(>>>):忽略符号位,前面的最高位以0补齐

          6、三目运算符:如:       

        int a = 9;
        boolean result = a>0 ?  true :  false;
        System.out.println(result);

                三目运算符和if-else的运算效率的比较:对于大数据来说,if-else的运算效率比三目运算符快,比如下面的例子:找出0-1亿内的偶数:

                 需要注意的是,可能会抛出java.lang.OutOfMemoryError: Java heap space异常,所以需要设置如下:


上图中,-Xms表示java heap的初始化大小,默认为物理内存的1/64,-Xmx表示java heap的最大值,建议设置为物理内存的一半

具体的代码如下:

                

               //jvm占用的所有内存
               long totalst=Runtime.getRuntime().totalMemory();
               System.out.println("Totalst:"+totalst/(1024*1024)+"mb");
               //jvm能够从操作系统获取的最大内存
               long maxst=Runtime.getRuntime().maxMemory();
               System.out.println("Max:"+maxst/(1024*1024)+"mb");
               //jvm中空闲的内存
               long freest=Runtime.getRuntime().freeMemory();
               System.out.println("Free:"+freest/(1024*1024)+"mb");
               System.out.println();
		long startTime = System.currentTimeMillis();
		
		List list = new ArrayList<>();
		
		for (int i = 0; i < 100000000; i++) {
			//把0——1000 0000zhong 的偶数找出来放到list
                        //三目运算符
			list.add(i % 2 == 0 ? i : null);;
		}
		long endTime = System.currentTimeMillis();
		
		long timeUsed = endTime - startTime;
		
		System.out.println("三目运算符的耗时 :" + timeUsed + "ms");
		
		long startTimes = System.currentTimeMillis();
		
		List lists = new ArrayList<>();
		
		for (int i = 0; i < 100000000; i++) {
			//把0——1000 0000zhong 的偶数找出来放到list
			
			//if-else
			if(i % 2 ==0){
				lists.add(i);
			}
			else {
				lists.add(null);
			}
		}
		long endTimes = System.currentTimeMillis();
		
		long timeUseds = endTimes - startTimes;
		
		System.out.println("if-else时 :" + timeUseds + "ms");
		
		System.out.println();
		//jvm占用的所有内存
                long total=Runtime.getRuntime().totalMemory();
                System.out.println("Total:"+total/(1024*1024)+"mb");
                //jvm能够从操作系统获取的最大内存
                long max=Runtime.getRuntime().maxMemory();
                System.out.println("Max:"+max/(1024*1024)+"mb");
                //jvm中空闲的内存
                long free=Runtime.getRuntime().freeMemory();
                System.out.println("Free:"+free/(1024*1024)+"mb");

                结果:

                        Totalst:1917mb
                        Max:3555mb
                        Free:1907mb


                        三目运算符的耗时 :19382ms
                        if-else时 :2008ms


                        Total:3917mb
                        Max:3917mb
                        Free:1132mb

          7、其他运算符:instanceof,用来在运行时指出对象是否为特定类(如Object)的一个实例

二、流程控制

        1、while循环

        2、do-while循环

        3、for的一般形式和增强型for循环:增强型for循环可以用foreach快速输入,它用于数组、集合遍历,不用声明数组长度和迭代器

              一般for循环和增强型for循环的比较:对于大数据的运算,增强型for循环比较快;对于小数据,二者的运行效率相差不大。如:
              

                long startTime = System.currentTimeMillis();
		String[] names = new String[50000000];
		int j = 0;
		for (String string : names) {
			string = "xiaoming" + j;
			j++;
		}
		long endTime = System.currentTimeMillis();
		
		System.out.println("增强型for循环的耗时:" + (endTime - startTime));
		
		long startTimes = System.currentTimeMillis();

		String[] xm = new String[50000000];
		for (int i = 0 ; i < xm.length;i++) {
			xm[i] = "xingming" + i;
		}
		long endTimes = System.currentTimeMillis();
		
		System.out.println("一般for循环的耗时:" + (endTimes - startTimes));
                               结果:
                                      增强型for循环的耗时:3194
                                      一般for循环的耗时:29892

        4、break和continue、return

              return:结束接下来的代码,默认是return 0 

三、数组

       1、引用数据类型

             数组中的每个元素的数据类型必须一致,但有例外,如Fruit xx = {new Apple9(),new Peach()};这里的Fruit是其他两个类的父类-->(类是一种引用数据类型)
              两种数组的赋值形式:      

                        Fruit [] fruits = new Fruit[]{
                                                                 new Apple(),
                                                                 new Peach()
                                                                };
                        或:
                        Fruit [] fruits = {
                                                   new Apple(),
                                                   new Peach()
                                                 };


          2、数组定义和初始化

               (1)定义
                    建议用:type [] assayName;
                    还可以声明如下:type arrayName [];
                    数组初始化之后才能使用,初始化就是为数组分配内存空间
              (2)初始化
                     静态初始化(已知每个值)
                     动态初始化 = new type[length];

         3、访问数组元素

               注意引发java.lang.ArrayIndexOutOfBoundsException异常的两种典型原因:下标为Integer.MAX_VALUE和下标为-1
        
               初始化内存不够:
                       String [] names = new String[Integer.MAX_VALUE];
                       System.out.println("数组的最大长度:" + names.length);
                抛出:Exception in thread "main" java.lang.OutOfMemoryError: Requested array size exceeds VM limit

                注意:引用数据类型的元素是引用,每个元素存储的还是引用。指向另一块内存

        4、Arrays的方法介绍

            (1)查找:binarySearch,如

           int [] a = {12,121,223,11};
           int b = Arrays.binarySearch(a, 12);
           System.out.println(b);

                   结果:

                            0
            (2)copyOf(int[] a.int ind length):复制制定数组,截取原数组的长度为length,如:          

           int [] a = {12,121,223,11};
           int [] b = Arrays.copyOf(a, 1);
           System.out.println(Arrays.toString(b));

                         结果:

                                 [12]
      (3)fill(int[] a, int fromIndex, int toIndex, int val) :将指定的 int 值分配给指定 int类 型数组指定范围(不包括toIndex对于的元素)中的每个元素。
               默认值:int类型->0;boolean类型->false;引用数据类型->null
               如:

           int [] a = new int[5] ;
           Arrays.fill(a, 1,4,1);
	   System.out.println(Arrays.toString(a));

                结果:

                         [0, 1, 1, 1, 0]      
         
             (4) sort(int[] a):按升序排序,如

          int [] a = {1,23,54,21};
          Arrays.sort(a);
	  System.out.println(Arrays.toString(a));
                     结果:

                             [1, 21, 23, 54]

               (5)toString:以字符串形式返回数组内容

四、查看jvm信息和代码段的创建、导入、导出

        1、查看jvm占用的内存、能够从操作系统获取的最大内存、空闲的内存

              //jvm占用的所有内存
                    long totalst=Runtime.getRuntime().totalMemory();
                    System.out.println("Totalst:"+totalst/(1024*1024)+"mb");
              //jvm能够从操作系统获取的最大内存
                    long maxst=Runtime.getRuntime().maxMemory();
                    System.out.println("Max:"+maxst/(1024*1024)+"mb");
              //jvm中空闲的内存
                    long freest=Runtime.getRuntime().freeMemory();
                    System.out.println("Free:"+freest/(1024*1024)+"mb");

        2、如何把上面的代码设置成代码块,以便以后快速输入

              (1)我使用的是myeclipse,打开windows->preferences->

              (2)

                 

                 (3)输入以下内容

                   

                  (4)确认,接着(也可以导入或将已存在的代码段导出):

                          

                      (5)以后想用到这段代码,就可以:

                       


五、对作业的思考

        我查看了舍友的三个作业,其中,发现他的数组去重方法代码比较少,也设计得比较有技巧、有效率,相比之下,我的数组去重的方法的操作过程的代码还是显得比较复杂,用了2个数组,可能对于大型数组,我的时间复杂度可能比较大,效率也会比较低。总之,通过比较、学习,进而总结不足,积累编写代码的经验,以后写代码的时候思路会更加清晰一点,也会更有效率地设计代码,从而让它更有效率地运行吧!

                       

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值