当前位置:文档之家› 黑马程序员入学测试题答案

黑马程序员入学测试题答案

黑马程序员入学测试题答案
黑马程序员入学测试题答案

1.定义一个交通灯枚举,包含红灯、绿灯、黄灯,需要有获得下一个灯的方法;

例如:红灯获取下一个灯是绿灯,绿灯获取下一个灯是黄灯。

publicenum Lamp {

RED("GREEN"),GREEN("YELLOW"),YELLOW("RED");

private String next;

private Lamp(String next){

this.next = next;

}

public Lamp nextLamp(){

return Lamp.valueOf(next);

}

}

2、写一个ArrayList类的代理,实现和ArrayList中完全相同的功能,并可以计算每个方法运行的时间。

publicclass test1 {

publicstaticvoid main(String[] args) {

final ArrayList target = new ArrayList();

List proxy = (List)Proxy.newProxyInstance(

List.class.getClassLoader(),

ArrayList.class.getInterfaces(),

new InvocationHandler() {

@Override

public Object invoke(Object proxy, Method method, Object[] args)

throws Throwable {

long beginTime = System.currentTimeMillis();

Thread.sleep(10);

Object reVal = method.invoke(target, args);

long endTime = System.currentTimeMillis();

System.out.println(method.getName()+" runing time is "+(endTime-beginTime));

return reVal;

}

});

proxy.add("nihaoa");

proxy.add("nihaoa");

proxy.add("nihaoa");

proxy.remove("nihaoa");

}

}

3. ArrayList list = new ArrayList();

在这个泛型为Integer的ArrayList中存放一个String类型的对象。publicclass test2 {

publicstaticvoid main(String[] args) throws Exception{

ArrayList list = new ArrayList();

Method method = list.getClass().getMethod("add", Object.class);

method.invoke(list, "i am a String");

System.out.println(list.toString());

}

}

4、一个ArrayList对象aList中存有若干个字符串元素,

现欲遍历该ArrayList对象,

删除其中所有值为"abc"的字符串元素,请用代码实现。

publicclass test4 {

publicstaticvoid main(String[] args) {

ArrayListaList = new ArrayList();

aList.add("abc");

aList.add("nihaoa");

aList.add("nihaoa");

aList.add("abc");

aList.add("cdb");

aList.add("abc");

aList.add("cdb");

System.out.println(aList.toString());

Iterator it = aList.iterator();

while(it.hasNext()){

String str = it.next();

if(str.equals("abc")){

it.remove();

}

}

}

}

5、编写一个类,增加一个实例方法用于打印一条字符串。

并使用反射手段创建该类的对象,并调用该对象中的方法。

publicclass test5 {

publicstaticvoid main(String[] args)throws Exception {

Classclazz = myClass.class;

Method method = clazz.getMethod("printStr", String.class);

method.invoke(clazz.newInstance(), "nihao ma? this my print str");

}

}

class myClass{

publicvoid printStr(String str){

System.out.println(str);

}

}

6 、存在一个JavaBean,它包含以下几种可能的属性:1:boolean/Boolean

2:int/Integer

3:String

4:double/Double 属性名未知,现在要给这些属性设置默认值,以下是要求的默认值:String类型的默认值为字符串https://www.doczj.com/doc/768213617.html, int/Integer类型的默认值为100 boolean/Boolean类型的默认值为true

double/Double的默认值为0.01D.

只需要设置带有getXxx/isXxx/setXxx方法的属性,非JavaBean属性不设置,请用代码实现publicclass test7 {

publicstaticvoid main(String[] args) throws Exception {

Class clazz = Class.forName("cn.heima.test.testBean");

Object bean = clazz.newInstance();

BeanInfobeanInfo = Introspector.getBeanInfo(clazz);

// System.out.println(beanInfo);

PropertyDescriptor[] propertyDescriptors = beanInfo

.getPropertyDescriptors();

for (PropertyDescriptorpd : propertyDescriptors) {

// System.out.println(pd);

// 获取属性名

Object name = pd.getName();

// 获取属性类型

Object type = pd.getPropertyType();

// 获取get方法

Method getMethod = pd.getReadMethod();

// 获取set方法

Method setMethod = pd.getWriteMethod();

if (!"class".equals(name)) {

if (setMethod != null) {

if (type == boolean.class || type == Boolean.class) {

setMethod.invoke(bean, true);

}

if (type == String.class) {

setMethod.invoke(bean, "https://www.doczj.com/doc/768213617.html,");

}

if (type == int.class || type == Integer.class) {

setMethod.invoke(bean, 100);

}

if (type == double.class || type == Double.class) {

setMethod.invoke(bean, 0.01D);

}

}

if (getMethod != null) {

System.out.println(type + " " + name + "="

+ getMethod.invoke(bean, null));

}

}

}

}

}

class testBean {

privateboolean b;

private Integer i;

private String str;

private Double d;

public Boolean getB() {

return b;

}

publicvoid setB(Boolean b) {

this.b = b;

}

public Integer getI() {

return i;

}

publicvoid setI(Integer i) {

this.i = i;

}

public String getStr() {

return str;

}

publicvoid setStr(String str) {

this.str = str;

}

public Double getD() {

return d;

}

publicvoid setD(Double d) {

this.d = d;

}

}

7、定义一个文件输入流,调用read(byte[] b)

方法将exercise.txt文件中的所有内容打印出来(byte数组的大小限制为5,不考虑中文编码问题)。

publicclass test8 {

publicstaticvoid main(String[] args) {

FileInputStreamfr = null;

try {

fr = new FileInputStream("d:/exercise.txt");

byte[] bt = newbyte[5];

int len = 0;

while((len = fr.read(bt))!=-1){

for (int i = 0; i

System.out.print((char)bt[i]);

}

}

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}finally{

if(fr!=null){

try {

fr.close();

} catch (IOException e) {

e.printStackTrace();

}finally{

fr = null;

}

}

}

}

}

8、编写一个程序,它先将键盘上输入的一个字符串转换成十进制整数,然后打印出这个十进制整数对应的二进制形式。

这个程序要考虑输入的字符串不能转换成一个十进制整数的情况,并对转换失败的原因要区分出是数字太大,还是其中包含有非数字字符的情况。提示:十进制数转二进制数的方式是用这个数除以2,余数就是二进制数的最低位,接着再用得到的商作为被除数去除以2 ,这次得到的余数就是次低位,如此循环,直到被除数为0为止。其实,只要明白了打印出一个十进制数的每一位的方式(不断除以10,得到的余数就分别是个位,十位,百位),就很容易理解十进制数转二进制数的这种方式。

publicclass test9 {

publicstaticvoid main(String[] args) {

Scanner sc = null;

while (true) {

sc = new Scanner(System.in);

String str = sc.nextLine();

int a = 0;

if (isOctNumers(str)) {

a = Integer.valueOf(str);

} else {

System.out.println("输入不正确,请重新输入");

continue;

}

System.out.println(toBinary(a));

sc.close();

}

}

privatestaticboolean isOctNumers(String str) {

try {

Integer.parseInt(str);

returntrue;

} catch (NumberFormatException e) {

returnfalse;

}

}

publicstatic String toBinary(Integer decimal) {

StringBuildersb = new StringBuilder();

int x = 0;

while (decimal != 0) {

x = decimal % 2;

decimal = (int) (decimal / 2);

sb.append(x);

}

sb.reverse();

return sb.toString();

}

}

9、金额转换,阿拉伯数字转换成中国传统形式。例如:101000001010 转换为壹仟零壹拾亿零壹仟零壹拾圆整

publicclass testt10 {

privatestaticfinalchar[] data = { '零', '壹', '贰', '叄', '肆', '伍', '陆',

'柒', '捌', '玖' };

privatestaticfinalchar[] units = { '圆', '拾', '佰', '仟', '万', '拾', '佰',

'仟', '亿', '拾', '佰', '仟' };

@SuppressWarnings("resource")

publicstaticvoid main(String[] args) {

while (true) {

Scanner sc = new Scanner(System.in);

long l = sc.nextLong();

System.out.println(convert(l));

}

}

publicstatic String convert(long money) {

StringBuffersbf = new StringBuffer();

int uint = 0;

while (money != 0) {

sbf.insert(0, units[uint++]);

sbf.insert(0, data[(int) (money % 10)]);

money = money / 10;

}

// 去零

return sbf.toString().replaceAll("零[仟佰拾]", "零").replaceAll("零+万", "万")

.replaceAll("零+亿", "亿").replaceAll("亿万", "亿零")

.replaceAll("零+", "零").replaceAll("零圆", "圆");

}

}

10.取出一个字符串中字母出现的次数。如:字符串:"abcde%^kka27qoq" ,输出格式为:a(2)b(1)k(2)...

publicclass test1 {

publicstaticvoid main(String[] args) {

String str = "abcdekka27qoA*&AAAq";

CountChar(str);

}

privatestaticvoid CountChar(String str) {

char[] c = str.toCharArray();

System.out.println(c);

Map map = new LinkedHashMap();

for (int i = 0; i

if ((c[i] <= 90 && c[i] >= 65)||(c[i]>=97&&c[i]<=112)) {

if (!(map.keySet().contains(c[i]))) {

map.put(c[i], 1);

} else {

map.put(c[i], map.get(c[i]) + 1);

}

}

}

StringBuildersb = new StringBuilder();

Iterator> it = map.entrySet().iterator();

while (it.hasNext()) {

Map.Entry entry = it.next();

sb.append(entry.getKey() + "(" + entry.getValue() + ")");

}

System.out.println(sb);

}

}

/**

*11、将字符串中进行反转。abcde -->edcba

*/

publicclass test5 {

publicstaticvoid main(String[] args) {

String str = "abcdgrdfgse";

System.out.println(reverse(str));

}

privatestatic String reverse(String str) {

String result = "";

char[] c = str.toCharArray();

for (int i = c.length-1; i >= 0 ; i--) {

result += c[i];

}

return result;

}

}

/**

* 12、

* 已知文件a.txt文件中的内容为“bcdeadferwplkou”,请编写程序读取该文件内容,并按照自然顺序排序后输出到b.txt文件中。即b

* .txt中的文件内容应为“abcd…………..”这样的顺序。

*/

publicclass test6 {

publicstaticvoid main(String[] args) {

FileInputStreamfis = null;

FileOutputStreamfos = null;

try {

fis = new FileInputStream("D:/a.txt");

fos = new FileOutputStream("D:/b.txt");

byte[] c = newbyte[fis.available()];

while (fis.read(c) != -1) {

Arrays.sort(c);

fos.write(c);

}

fos.flush();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} finally {

try {

fis.close();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

try {

fos.close();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

}

/**

* 13、编写一个程序,获取10个1至20的随机数,要求随机数不能重复。*/

publicclass test7 {

publicstaticvoid main(String[] args) {

System.out.println(getRandom());

}

publicstatic ListgetRandom() {

Random rd = new Random();

ArrayList al = new ArrayList();

int i = 0;

while(i!=10){

int r = rd.nextInt(20);

if(!al.contains(rd)){

al.add(r);

i++;

}

}

return al;

}

}

/**

* 14、编写三各类Ticket、SealWindow、TicketSealCenter分别代表票信息、售票窗口、售票中心。售票中心分配一定数量的票,

* 由若干个售票窗口进行出售,利用你所学的线程知识来模拟此售票过程。

*/

publicclass test8 {

publicstaticvoid main(String[] args) {

Ticket ticket = Ticket.getInstance();

ticket.setNumber(1000);

new SealWindow("1号窗口").start();

new SealWindow("2号窗口").start();

new SealWindow("3号窗口").start();

new SealWindow("4号窗口").start();

}

}

class Ticket {

privatestatic Ticket ticket = new Ticket();

private Ticket() {

}

publicstatic Ticket getInstance() {

return ticket;

}

privateint number;

publicvoid setNumber(int number) {

this.number = number;

}

publicint getNumber() {

return number;

}

publicboolean isHasTicket() {

if (number > 0)

returntrue;

returnfalse;

}

publicvoid sealTicket() {

number--;

}

}

class SealWindow {

private String name;

public SealWindow(String name) {

https://www.doczj.com/doc/768213617.html, = name;

}

publicvoid start() {

Executors.newScheduledThreadPool(1).execute(new Runnable() { Ticket ticket = Ticket.getInstance();

@Override

publicvoid run() {

while (ticket.isHasTicket()) {

synchronized (Ticket.class) {

if(!ticket.isHasTicket())continue;

try {

Thread.sleep(10);

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

ticket.sealTicket();

System.out.println(name + "售出"

+ (ticket.getNumber() + 1) + "号票");

}

}

}

});

}

}

class TicketSealCenter {

}

/**

*

* 15、自定义枚举Week 用于表示星期,Mon,Tue,Wed...要求每个枚举值都有toLocaleString * 方法,用于获得枚举所表示的星期的中文格式星期一、星期二、星期三...

*

*/

publicenum Week {

Mon {

@Override

public String toLocaleString() {

return "星期一";

}

},Tue {

@Override

public String toLocaleString() {

return "星期二";

}

},Wed {

@Override

public String toLocaleString() {

return "星期三";

}

},Thu {

@Override

public String toLocaleString() {

return "星期四";

}

},Fri {

@Override

public String toLocaleString() {

return "星期五";

}

},Sat {

@Override

public String toLocaleString() {

return "星期六";

}

},Sun {

@Override

public String toLocaleString() {

return "星期天";

}

};

/*private String next;

private Week(String next){

}*/

publicabstract String toLocaleString();

}

/**

* 16、已知一个int类型的数组,用冒泡排序法将数组中的元素进行升序排列。* @author Administrator

*

*/

publicclass test1 {

publicstaticvoid main(String[] args) {

//定义一个数组

int[] arr = newint[]{2,1,5,4,6,4,5,4,5,4,10,9};

//调用BubbleSort方法对数组进行排序

BubbleSort(arr);

//输出排序后的数组

System.out.println(Arrays.toString(arr));

}

/**

* 这一个使用冒泡排序使int型数组内元素按照升序重新排序的算法

* @param arr接收一个int型数组

*/

publicstaticvoid BubbleSort(int[] arr){

//定义一个临时变量

int temp = 0;

for (int i = arr.length - 1; i > 0; --i) {

for (int j = 0; j < i; ++j) {

if (arr[j] >arr[j+1]) { //重复比较相邻元素,如果前一个比后一个大,则交换.

//利用中间变量temp,对arr[j]和arr[j+1]对换

temp = arr[j];

arr[j] = arr[j + 1];

arr[j + 1] = temp;

}

}

}

}

}

相关主题
文本预览
相关文档 最新文档