黑马程序员_入学测试题详解

----------------------ASP.Net+Android+IOS开发.Net培训、期待与您交流!----------------------

package com.itheima;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
/*
   题目:ArrayList<Integer> list = new ArrayList<Integer>(); 在这个泛型为Integer的ArrayList中存放一个String类型的对象。
   分析:
  	1.定义Integer泛型
  	2.取得list的所有方法
  	3.遍历打印list的方法
  	4.通过反射来执行list的第一个方法,第一个是list对象,代表该对象的方法,第二个是方法参数
   步骤:
    1.List<Integer> list = new ArrayList<Integer>();
    2.Method[] method=list.getClass().getMethods();
    3.method[i]
    4.method[1].invoke(list, str);
 */
public class Test1 {
	public static void main(String[] args) throws Exception {
		List<Integer> list = new ArrayList<Integer>(); //定义Integer泛型
		
			String str = "abc"; 
			
			Method[] method=list.getClass().getMethods();//取得list的所有方法
			
			System.out.println(method.length);
			
		for(int i=0;i<method.length;i++){
			
			System.out.println(method[i]);//遍历打印list的方法
			
		}
			method[1].invoke(list, str);//通过反射来执行list的第一个方法,第一个是list对象,代表该对象的方法,第二个是方法参数
			
			System.out.println(list.size());
			
		for(int i=0;i<list.size();i++){
			
			System.out.println(list.get(i));
			
		}
	}

}


package com.itheima;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/*
  題目:编写一个类,在main方法中定义一个Map对象(采用泛型),加入若干个对象,然后遍历并打印出各元素的key和value。
  分析:
  	1.创建Map对象  
  	2.加入若干对象  
  	3.遍历Map对象 
  	4.打印元素key和value 
  步骤:
  	1.Map<String,Integer> map = new HashMap<String,Integer>();
  	2.map.put("小明", 21);
  	3.while(it.hasNext()){  
	            Map.Entry<String,Integer> me = it.next();  
	        } 
  	4.System.out.println("key:"+me.getKey()+"------"+"value:"+me.getValue());
  
 */
public class Test2 {
	 public static void main(String[] args) {  
	        //创建Map对象  
	        Map<String,Integer> map = new HashMap<String,Integer>();  
	        
	        //加入若干对象  
	        map.put("小明", 21);  
	        map.put("小王", 18);
	        map.put("小李", 45);
	        //遍历Map对象  
	        Set<Map.Entry<String,Integer>> set = map.entrySet();  
	        
	        Iterator<Map.Entry<String,Integer>> it = set.iterator();
	        
	        while(it.hasNext()){  
	            Map.Entry<String,Integer> me = it.next(); 
	            
	            //打印元素key和value  
	            System.out.println("key:"+me.getKey()+"------"+"value:"+me.getValue());  
	        }  
	 }
}


package com.itheima;

import java.lang.reflect.Method;

/*
  题目:方法中的内部类能不能访问方法中的局部变量,为什么?
           答:方法中的内部类访问局部变量的时候,局部变量需要被 final 关键字修饰。
           因为方法中的代码是由上而下顺序执行的,方法运行结束后,局部变量就被销毁,
           内部类的生命周期可能会比局部变量的生命周期长;看下面的代码,方法中的内部
           类 Inner.class 调用方法中的局部变量 x ,正常调用的时候内部类能够调用到方
           法中的局部变量,并将内部类对象 inner 返回,正常调用结束后,如果方法中的局
           部变量 x 没有被 final 关键字修饰,x 则会被销毁,我们再通过反射的方式去调用 x 
           的时候则会发现找不到变量 x ,如果局部变量 x 被 final 关键字修饰后,则 x 在方
           法运行结束后不会被销毁,而是常驻在内存中直到 JVM 退出,这样再通过反射调用的
           时候依然可以找到 x 。
 */
public class Test3 {
	public static void main(String[] args) throws Exception {
		Outer outer = new Outer(); // 正常调用
		Object object = outer.outerfun();

		Class clazz = object.getClass(); // 反射调用
		Method method = clazz.getMethod("innerfun");
		method.invoke(object);
	}
}

	class Outer {
		public Object outerfun() {
			final int x = 5;
		class Inner {						//内部类Inner
			public void innerfun() {
				System.out.println(x);
			}
		}
			Inner inner = new Inner();
			inner.innerfun();
			return inner;
		}
	
}


package com.itheima;
/*
  题目:定义一个交通灯枚举,包含红灯、绿灯、黄灯,需要有获得下一个灯的方法,例如:红灯获取下一个灯是绿灯,绿灯获取下一个灯是黄灯。
  分析:
 	1.定义一个交通灯类TrafficLights,用abstract修饰
 	2.构造方法私有化,目的是不允许程序员自己创建该类的对象。
 	3.使用new TrafficLights();枚举出红灯、绿灯、黄灯。
 	4.创建获取下一个灯的方法nextLight(),用abstract修饰。
 	5.重载toString()方法。
 	6.6.在主函数中调用获取下一个交通灯的方法
  步骤:
  	1.abstract class TrafficLights{}
  	2.private TrafficLights(){}
  	3.public final static TrafficLights REDLIGHT=new TrafficLights();
  	4.public abstract TrafficLights nextLight();
  	5.public String toString();
  	6.TrafficLights.YELLOWLIGHT.nextLight();
 */
abstract class TrafficLights{
	private TrafficLights(){				//构造方法私有化,目的是不让程序员自己创建该类的对象。
		
	}
	public final static TrafficLights REDLIGHT=new TrafficLights(){		//定义红灯的静态变量
		public TrafficLights nextLight(){								//重载nextLight()方法
			return GREENDLIGHT;
		}
	};
	public final static TrafficLights GREENDLIGHT=new TrafficLights(){	//定义绿灯的静态变量
		public TrafficLights nextLight(){								//重载nextLight()方法
			return YELLOWLIGHT;
		}
	};
	public final static TrafficLights YELLOWLIGHT=new TrafficLights(){	//定义黄灯的静态变量
		public TrafficLights nextLight(){								//重载nextLight()方法
			return REDLIGHT;
		}
	};
	public abstract TrafficLights nextLight();							//获取下一个交通灯的方法
/*	
 	//第一种方法,由于有太多的if....else判断,需要写的代码太多,不可取。
	public TrafficLights nextLight(){
		if(this==REDLIGHT){
			return GREENDLIGHT;
		}else if(this==GREENDLIGHT){
			return YELLOWLIGHT;
		}else{
			return REDLIGHT;
		}
	}
*/
	public String toString(){					//重载toString()方法
		if(this==REDLIGHT){
			return "红灯";
		}else if(this==GREENDLIGHT){
			return "绿灯";
		}else{
			return "黄灯";
		}
	}
}
public class Test4 {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//主函数中调用获取下一个交通灯的方法nextLight();
		System.out.println(TrafficLights.YELLOWLIGHT.nextLight());
	}

}


package com.itheima;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

/*
  题目:编写一个类,增加一个实例方法用于打印一条字符串。并使用反射手段创建该类的对象, 并调用该对象中的方法
  分析:
   1.加载类 Sample
   2.加载无参构造方法  
   3.创建Sample对象  
   4.获得自定义的实例方法 
   5.调用自定义的实例方法   
  
  步骤:
   1.Class clazz = Class.forName("com.itheima.Sample"); 
   2.Constructor constructor = clazz.getConstructor(null);
   3.Sample s = (Sample) constructor.newInstance(null); 
   4.Method method = clazz.getMethod("say", null);
   5.method.invoke(s, null);
  
 */
public class Test5 {
	 public static void main(String[] args){  
	        try {  
	            //加载类  
	            Class clazz = Class.forName("com.itheima.Sample");  
	            //加载无参构造方法  
	            Constructor constructor = clazz.getConstructor(null);  
	            //创建Sample对象  
	            Sample s = (Sample) constructor.newInstance(null);  
	            //获得自定义的实例方法  
	            Method method = clazz.getMethod("say", null);  
	            //调用该方法  
	            method.invoke(s, null);  
	        } catch (Exception e) {  
	            e.printStackTrace();  
	        }   
	    }
}


package com.itheima;

public class Sample {
	//实例方法  
	 public void say(){ 
		 System.out.println("老师您好,老师审批辛苦了!");  
	 } 
	

}


package com.itheima;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

/*
   题目:把当前文件中的所有文本拷贝,存入一个txt文件,统计每个字符出现的次数并输出,例如:

        a:  21 次 
        b:  15 次
        c:: 15 次
                    把:  7 次
                    当:  9 次
                    前:  3 次
                     ,:30 次
 */
public class Test6 {
	public static void main(String[] args) throws IOException {  
        // 读取文本内容   
        BufferedReader in = new BufferedReader(new FileReader("E:\\exam.txt"));  
        String str = null;
        String	s2 = new String();  
        while ((s2 = in.readLine()) != null)  
            str = str+s2;						// 如果s2不为空,将s2中的读到的每一行给str  
        	in.close();  
        int len = 0;  
        while (str.length() > 0) {  
            len = str.length(); 					 // 获取第一个字符  
            String s = str.substring(0,1);			 // 用空格替换,以便计算这个字符的个数  
            str = str.replaceAll(s, ""); 			 // 写入文件  
            System.out.println("["+s+"]" + "  出现  " + (len - str.length())+" 次");  
  
        }  
    }

}


package com.itheima;
/*
 题目:将字符串中进行反转。abcde --> edcba
 分析:
 	1.定义一个反转字符串的方法,返回值类型为String
 	2.将字符串转换成字符,保存在字符数组char [] chars中。
 	3.确定字符数组的首尾
 	4.对字符串进行换位置操作。
 	5.在主函数中调用reverser()方法,并传入字符串"abcde"
 步骤:
 	1.public static String reverser(String str){}
 	2.char [] chars=str.toCharArray();
 	3.int start=0;   int end=chars.length-1;
 	4.对换位置的功能进行抽取,提高代码的复用性,抽取出swap()方法。
 	  temp=chars[end];
	  chars[end]=chars[start];
	  chars[start]=temp;
 	5.reverser("abcde");
 */
public class Test7 {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println("反转后的字符串是:"+reverse("abcde"));
	}
	// 反转字符串的方法  
    private static String reverse(String str) {  
          
        // 字符串转成字符数组  
        char[] arr = str.toCharArray();  
          
        // 对字符数组进行反转  
        for (int start = 0, end = arr.length - 1; start <= end; start++, end--) {  
            swap(arr, start, end);  
        }  
        // 返回字符串  
        return new String(arr);  
    }  
    // 功能抽取,提高复用性  
    private static void swap(char[] arr, int start, int end) {  
        char temp = arr[start];  
        arr[start] = arr[end];  
        arr[end] = temp;  
    } 

}


package com.itheima;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

/*
  题目:编写程序,循环接收用户从键盘输入多个字符串,直到输入“end”时循环结束,并将所有已输入的字符串按字典顺序倒序打印。
    分析:
  	 1.字符串本身提供的比较性为字典顺序,可以使用工具类Collections.reverse()方法将原来的比较性反序。
                     但也可以自定一个比较器,让集合自身必备比较性; 
     2.键盘录入的是字节流,操作的是字符流,可以使用转换流,并加入缓冲区技术,提高效率; 
     3.录入的字符串存储到ArrayList集合中; 
     4.使用Collections工具类给ArrayList中元素排序 
     5.打印ArrayList集合中的元素 
    步骤:
  	 1.List<String> list = new ArrayList<String>(); 
  	 2.BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
  	 3.list.add(line); 
  	 4.Collections.sort(list, Collections.reverseOrder()); 
  	 5.Iterator<String> it = list.iterator();  
        while(it.hasNext()){  
            System.out.println(it.next());  
        }  
 */
public class Test8 {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		// 1、定义一个ArrayList集合  
        List<String> list = new ArrayList<String>();  
  
        // 键盘录入字符串,转换流,缓冲区  
        System.out.println("请输入一些字符或者字符串, end 结束!");
        BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));  
        String line = null;  
        try {  
            while ((line = bufr.readLine()) != null) {  
                if ("end".equals(line))  
                    break;  
                // 往ArrayList集合中添加元素  
                list.add(line);  
            }  
        } catch (IOException e) {  
            throw new RuntimeException("IO异常");  
        }  
        // 给ArrayList排序,字典倒序  
        Collections.sort(list, Collections.reverseOrder());  
        // 打印集合  
        Iterator<String> it = list.iterator();  
        while(it.hasNext()){  
            System.out.println(it.next());  
        }  
	}
}


package com.itheima;
/*
  题目:写一方法,打印等长的二维数组,要求从1开始的自然数由方阵的最外圈向内螺旋方式地顺序排列。 如: n = 4 则打印:                                
		1	2	3	4
		12	13	14	5
		11	16	15	6
		10	9	8	7
 分析:递归为二维数组赋值 
 	  arr 二维数组
 	  n  控制递归次数 
 	  count 计算圈数 最外圈为0
 	  max  开始循环值:
 
 
 */
public class Test9 {
	public static void main(String[] args) {  
        //调用打印从1开始的自然数由方阵的最外圈向内螺旋方式地顺序排列的二维数组方法  
        arrPrint(4);  
    }  
    //打印从1开始的自然数由方阵的最外圈向内螺旋方式地顺序排列的二维数组  
    public static void arrPrint(int num){  
        //定义定长二维数组  
        int[][] arr = new int[num][num];  
        int n = arr.length;  
        int count = 0;  
        int max = 0;  
        //递归为二维数组赋值  
        rec2DArr(arr,n,count,max);  
        //打印  
        print2DArr(arr);  
    }  
    public static void rec2DArr(int[][] arr,int n,int count,int max){  
        //递归控制条件  
        if(n>0){  
            //纵坐标控制值  
            int k = 0;  
            //(n-1)*4代表每一圈的数值范围  
            for(int i=0;i<(n-1)*4;i++){  
                //在上边赋值  
                if(i<n-1){  
                    arr[count+0][count+i] = ++max;  
                }  
                //向右边赋值  
                else if(i<2*n-2){  
                    arr[count+k++][arr.length-1-count]=++max;  
                }  
                //在下边赋值  
                else if(i<3*n-3){  
                    arr[arr.length-1-count][(k--)+count]=++max;  
                }  
                //向左边赋值  
                else if(i<4*n-4){  
                    arr[arr.length-1-(k++)-count][0+count]=++max;     
                }  
            }  
            //当n为奇数时,存在n=1的情况,最里圈只有一个数  
            if(n==1){  
                arr[arr.length/2][arr.length/2]=max+1;  
            }  
            //增加圈数  
            count++;  
            //边界每次减少两个数值  
            n -= 2;  
            //递归  
            rec2DArr(arr,n,count,max);  
        }  
    }  
    //打印二维数组  
    public static void print2DArr(int[][] arr){  
        //二维数组需要双重循环打印  
        for(int[] ar : arr){  
            for(int a : ar){  
                if(a<10)  
                    System.out.print(" "+a+" ");  
                else  
                    System.out.print(a+" ");  
            }  
            System.out.println();  
        }  
    }  

}


package com.itheima;
/*
 题目:28人买可乐喝,3个可乐瓶盖可以换一瓶可乐,那么要买多少瓶可乐,够28人喝?假如是50人,又需要买多少瓶可乐?(需写出分析思路)
   
 分析:当拿3个瓶盖去换一瓶可乐,多了一瓶可乐同时又多了一个瓶盖, 
                再买两瓶可乐,换取一瓶可乐同时多了一个瓶盖,循环..直到够所有人喝到可乐为止。
      
                定义一个获取可乐瓶数的方法,传入人数
                通过上面的分析,开始计算需要的可乐数目。
      
 
 步骤:
     1. public static int countCokes(int num);
     2. for(int i=0;i<num;i++){  
            if(cap!=3){
                sum++;  
                cap++;  
            }  
            else if(cap==3){  
                cap = 1;  
            }  
        }
      
 */
public class Test10 {
	public static void main(String[] args) {  
		
        System.out.println("28人喝可乐,需要购买:"+countCokes(28)+"瓶可乐");
        
        System.out.println("50人喝可乐,需要购买:"+countCokes(50)+"瓶可乐");  
        
    }  
    //购买可乐方法  
    public static int countCokes(int num){  
        //瓶盖数  
        int cap = 0;  
        //需要购买瓶数  
        int sum = 0;  
        for(int i=0;i<num;i++){  
            if(cap!=3){  
                //购买一瓶  
                sum++;  
                //同时瓶盖增加一个  
                cap++;  
            }  
            else if(cap==3){  
                cap = 1;  
            }  
        }  
        return sum;  
    } 

}


----------------------ASP.Net+Android+IOS开发.Net培训、期待与您交流!----------------------

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值