java基础一些题目


package com.itheima;

import java.lang.reflect.Method;
import java.util.ArrayList;

/**
 * 第1题: ArrayList<Integer> list = new ArrayList<Integer>(); 
 * 在这个泛型为Integer的ArrayList中存放一个String类型的对象。
 */
public class Test1 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//创建集合对象,泛型为Integer
		ArrayList<Integer> list=new ArrayList<Integer>();
		
		//添加元素,自动装箱功能把int转变成Integer类型
		list.add(1);
		list.add(2);
		list.add(3);
		
		//声明Method成员
		Method methodAdd;
		try {
			//有ArrayList的字节码,获得其add方法
			methodAdd=ArrayList.class.getMethod("add", Object.class);
			//调用其invoke()方法,向list对象中添加字符串"你好"
			methodAdd.invoke(list, "你好");
			//获得集合中的第4个元素,并输出
			System.out.println(list.get(3));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}

}
|
package com.itheima;
/**
 * 第2题:方法中的内部类能不能访问方法中的局部变量,为什么?
 */


/*
 * 内部类可以直接访问外部类,包括私有(private)
 * 之所以可以直接访问外部类中的成员,是因为内部类中持有了一个外部类的引用。
 * 写法为:外部类名.this.外部成员名.
 * 
 * 外部类访问内部类,必须建立内部类对象。
 */
public class Test2 {
    private int count;
    private String name;
    public class Citizen{
        private int count;
        private String name;
        public void output(int count){
            count++;
            this.count++;
            Test2.this.count++;
            System.out.println("output()方法中局部变量count为:" + count);
            System.out.println("内部类的成员变量count为:" + this.count);
            System.out.println("外部类的成员变量count为:" + Test2.this.count);
        }
    }
    Citizen citizen = new Citizen();
    public void increase(int s){
        citizen.output(s);
    }

   
    public static void main(String[] args) {
        // TODO code application logic here
        Test2 test = new Test2();
        test.count = 5;
        test.increase(1);
    }
}
|
package com.itheima;

/**
 * 第3题:
 * 		 分析运行结果,说明原理。(没有分析结果不得分)
 * 
 */


/*
 * 此题的结果为:
 * 102
 * 102
 * 102
 * 原因:
 * 	用for循环向集合类中添加3个元素,而且这三个元素是同一个对象,
 * 	当向集合类中添加元素时,每次都向那个对象的成员变量val的赋值,当最后一赋值后,那个变量val的值就为102
 * 当遍历集合时:相当于执行了三次System.out.println(data.val);
 * 所以打印出的结果三个102了
 */

import java.util.ArrayList;
class Data {
    int val;
}

public class Test3 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		//创建Data的实例对象
		 Data data = new Data();
		 //创建集合类ArrayList类的实例对象,泛型为:Data
         ArrayList<Data> list = new ArrayList<Data>();

         for (int i = 100; i < 103; i++) {
        	 data.val = i;
        	 //添加元素
        	 list.add(data);
         }

         //遍历list对象中的元素
         for (Data d : list) {
        	 System.out.println(d.val);
         }
	}

}
|
package com.itheima;

import java.io.File;

/**
 * 第4题:请说明Java中字符'\'的含义,有什么作用?
 */
public class Test4 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		/*
		 * '\'是java中的转义字符,使用转义字符是为了避免出现二义性
		 * Java中的很多操作,例如文件操作等,需要用到路径这个东西,
		 * 比如:com\itheima,这个路径一般是以字符串表示的,
		 * 但问题来了,JAVA不知道你的\号到底是路径中的下一层的意思,还是字符串"\"的意思。
		 * 所以正确的写法是:com\\itheima
		 * 
		 * 又例如:有些字符(如回车符)不能通过键盘输入到字符串中,这是就需要用到转义字符常量
		 * 如:'\n'--换行,'\b'--退格,'\t'--水平制表,'\''--单引号,'\"'--双引号
		 */
		
		
		File file=new File("com\\itheima");
		
		char c1='\"';
		char c2='\'';
		System.out.print(c1+""+'\n'+c2+'\t'+'\\');
	}

}
|
package com.itheima;
/**
 * 第5题:
 * 存在一个JavaBean,它包含以下几种可能的属性:
       1:boolean/Boolean
       2:int/Integer
       3:String
       4:double/Double
     属性名未知,现在要给这些属性设置默认值,以下是要求的默认值:
       String类型的默认值为字符串 www.itheima.com
       int/Integer类型的默认值为100
     boolean/Boolean类型的默认值为true
       double/Double的默认值为0.01D.
  只需要设置带有getXxx/isXxx/setXxx方法的属性,非JavaBean属性不设置,请用代码实现

 */
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
/*
 * 解题思路:
 * 1.先获得JavaBean的所有方法
 *  	Mehtod [] methods=Class.getMethods();
 * 2.根据获得的方法,获得这些方法的方法名
 * 		String name=method.getName();
 * 3.由if else语句获取getXxx/isXxx/setXxx等方法,截取出成员变量的名字,并传给描述Java Bean的类PropertyDescriptor,再获得其Set方法
 * 		propertieName=name.substring(2)||name.substring(3)
 * 		pd=new PropertyDescriptor(propertieName.toLowerCase(), myBean.getClass());
 * 		pd.getWriteMethod();
 * 4.再根据上面获得method获得其参数类型的字节码,如果与已知字节码相同,就执行mehtod的invoke()方法,去执行myBean底层的方法
 * 		if(meth.getParameterTypes()[0]==cls)
			meth.invoke(myBean, value);
 */
public class Test5 {

	public static void main(String[] args) throws Exception{
		// TODO Auto-generated method stub
		MyBean myBean=new MyBean();
		
		Class [] cls={String.class,int.class,double.class,boolean.class};
		Object [] value={"www.itheima.com",100,0.01d,true};
		
		for(int i=0;i<cls.length;i++)
			setAttribute(myBean, cls[i], value[i]);
		
		/*setAttribute(myBean,boolean.class,true);
		setAttribute(myBean,int.class,100);
		setAttribute(myBean,String.class,"www.itheima.com");
		setAttribute(myBean,double.class,0.01d);*/
		System.out.println(myBean);
	}

	
	public static void setAttribute(MyBean myBean,Class cls,Object value)
			throws IntrospectionException, IllegalAccessException,
			InvocationTargetException {
		//获得类的所有方法
		Method[] methods=myBean.getClass().getMethods();
		for(Method method:methods){
			//获得方法的名字
			String name=method.getName();
			
			String propertieName=null;
			PropertyDescriptor pd=null;
			Method meth=null;
			
			//只获取getXxx/isXxx/setXxx等方法
			if(name.startsWith("is")){
				//获取获取getXxx/isXxx/setXxx等方法的成员变量名
				propertieName=name.substring(2);
				
				//获取描述java Bean类的对象,并传入的java Bean的成员变量名
				pd=new PropertyDescriptor(propertieName.toLowerCase(), myBean.getClass());
				meth=pd.getWriteMethod();
				
				//如果与传入的参数的字节码一致,就执行invoke方法
				if(meth.getParameterTypes()[0]==cls)
					meth.invoke(myBean, value);
			}
			else if((name.startsWith("set")||name.startsWith("get"))&&(!name.endsWith("Class"))){
				propertieName=name.substring(3);
				
				pd=new PropertyDescriptor(propertieName.toLowerCase(), myBean.getClass());
				meth=pd.getWriteMethod();
				
				if(meth.getParameterTypes()[0]==cls)
					meth.invoke(myBean, value);
			}
		}
		
		
	}
}


class MyBean{
	//声明成员变量
	private String name;
	private int age;
	private double score;
	private boolean boo;
	
	
	
	//其他干扰方法
	public void add(int age,int score){
		this.age+=age;
		this.score+=score;
	}
	
	public  void print(int age,double score,boolean boo)
	{
		System.out.println("....");
	}
	
	//get和set方法
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public double getScore() {
		return score;
	}
	public void setScore(double score) {
		this.score = score;
	}
	public boolean isBoo() {
		return boo;
	}
	public void setBoo(boolean boo) {
		this.boo = boo;
	}
	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return this.name+"..."+this.age+"..."+this.score+"..."+this.boo;
	}
}
|
package com.itheima;
/**
 * 第6题:分析以下程序运行结果,说明原理。(没有分析结果不得分)
 * 
 */
public class Test6 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		/*
		 * 在主线程里,用MyThread类(该类继承了Thread类)创建了一个的对象
		 * 先调用了这个对象的run方法(此时这个方法只算是一个普通的方法而已),休眠三秒后,输出B
		 * 然后启动一个新线程(命名为:thread_1),启动后,这个线程休眠了三秒,此时cpu转而执行主线程里的程序,就输出了A,输出完后,Thread_1线程还没有结束休眠
		 * 等休眠时间到后,就输出了B,此时整个程序结束
		 */
		MyThread t = new MyThread();
        t.run();
        t.start();//启动一个新线程
        System.out.println("A");

	}

}

class MyThread extends Thread {
    public void run() {
        try {
        	//休眠3秒
            Thread.sleep(3000);
            } catch (InterruptedException e) {
         }
        System.out.println("B");
        }
}
|
package com.itheima;
/**
 * 第7题:将字符串中进行反转。abcde --> edcba
 */
public class Test7 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String str="abcde";
		System.out.println("源字符串:"+str);
		
		StringBuilder sb=new StringBuilder(str);
		sb.reverse();//调用StringBuilder的反转方法
		
		str=sb.toString();
		System.out.println("反转后的字符串:"+str);
	}

}
|
package com.itheima;

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

/**
 * 第8题:定义一个标准的JavaBean,名叫Person,包含属性name、age。
 * 使用反射的方式创建一个实例、调用构造函数初始化name、age,使用反射方式调用setName方法对名称进行设置,
 * 不使用setAge方法直接使用反射方式对age赋值。
 */
public class Test8 {

	public static void main(String[] args) throws Exception{
		// TODO Auto-generated method stub
		
		//根据Person类的字节码,来返回其有参构造方法的Constructor对象con
		Constructor<Person> con= Person.class.getConstructor(String.class,int.class);
		
		//调用con的newInstance方法,创建构造方法的声明类的Person实例
		Person p=con.newInstance("zhangsan",20);
		System.out.println(p);
		
		
		//由Person类的字节码,获得一个Mehtod对象,此对象反应的Person类的setName方法
		Method methodSetName=Person.class.getMethod("setName", String.class);
		//有method的invoke方法,调用person类的setname方法
		methodSetName.invoke(p, "wagnwu");
		
		
		Method methodSetAge=Person.class.getMethod("setAge", int.class);
		methodSetAge.invoke(p, 22);
		
		
		System.out.println(p);
	}

}

class Person{
	private String name;
	private int age;
	
	
	public Person(String name, int age) {
		this.name = name;
		this.age = age;
	}


	public String getName() {
		return name;
	}


	public void setName(String name) {
		this.name = name;
	}


	public int getAge() {
		return age;
	}


	public void setAge(int age) {
		this.age = age;
	}


	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return this.name+"..."+this.age;
	}
	
	
	
	
}
|
package com.itheima;

/**
 *  第9题:使用TCP协议写一个可以上传文件的服务器和客户端。
 */
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Test9 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
	}

}

/*
 * 
 * 客户端:
 * 	1.建立socket服务,指定要连接主机和端口
 * 	2.获取socket流中的输出流。将数据写到该流中,通过网络发送给服务端。
 * 	3.获取socket流中的输入流,将服务端反馈的数据获取到,并打印
 * 	4.关闭客户端资源。
 */

class FileUploadClient{
	public static void main(String[] args)throws Exception{
		// TODO Auto-generated method stub
		//创建客户端的SOcket服务。指定目的主机和端口
		
		Socket s=new Socket("192.168.1.111",10007);
		
		//用传来的参数来当作要出入文件的路径
		File file=new File(args[0]);
		
		//创建文件读入流对象
		FileInputStream fis=new FileInputStream(file);
		
		//获取Socket流中的输出流。
		OutputStream out=s.getOutputStream();
		
		byte [] buf=new byte[1024];
		
		int len=0;
		while((len=fis.read(buf))!=-1)
		{
			out.write(buf,0,len);
			out.flush();
		}
		//文件传输结束,向客户端发送结束标记
		s.shutdownOutput();
		//获取Socket流中的输入流。
		InputStream in=s.getInputStream();
		
		byte[] bufin=new byte[1024];
		int num=in.read(bufin);
		System.out.println(new String(bufin,0,num));
		fis.close();
		s.close();
	}
}



/*
 * 服务端:
 * 那么为了可以让多个客户端同时并发访问服务端。
 * 那么服务端就将每个客户端封装到一个单独的线程中,这样,就可以同时处理多个客户端请求。
 * 
 */

class PicThread implements Runnable{
	private Socket s;
	PicThread(Socket s){
		this.s=s;
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		//获得起IP地址
		String ip=s.getInetAddress().getHostAddress();
		try {
			
			System.out.println(ip+"...connected");
			
			int count=0;
			//用其ip地址作为文件的名字 例如:192.168.1.111(0).txt
			File file=new File("D:\\b\\"+ip+"("+(count)+").jpg");
			
			//如果和已有的文件重名,则利用计数器的方式,来为其命名
			while(file.exists()){
				file=new File("D:\\b\\"+ip+"("+(count++)+").jpg");
			}
			
			
			
			InputStream in=s.getInputStream();
			
			FileOutputStream fos=new FileOutputStream(file);
			
			byte[]buf=new byte[1024];
			int len=0;
			while((len=in.read(buf))!=-1)
			{
				fos.write(buf,0,len);
				
			}
			OutputStream out=s.getOutputStream();
			out.write("上传成功".getBytes());
			fos.close();
			s.close();
		} catch (Exception e) {
			// TODO: handle exception
			throw new RuntimeException(ip+"...失败了");
		}
	}
	
}


class FileUploadServer{
	public static void main(String[] args)throws Exception{
		// TODO Auto-generated method stub
		//建立服务器段Socket服务,幷监听一个端口
		ServerSocket ss=new ServerSocket(10007);
		while(true){
			//通过accept方法来获取连接过来的客户端对象
			Socket s=ss.accept();
			//创建一个新线程,并启动
			new Thread(new PicThread(s)).start();;
		}
		
	}
}
|
package com.itheima;
/**
 * 第10题:有100个人围成一个圈,从1开始报数,报到14的这个人就要退出。然后其他人重新开始,从1报数,到14退出。
 * 问:最后剩下的是100人中的第几个人?
 */
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;

public class Test10 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//74   23
		/*ArrayList<Integer> al=new ArrayList<Integer>();
		for(int i=1;i<=100;i++)
			al.add(i);
		int i=0;
		while(al.size()!=1)
		{
			if(i==14&&i>=al.size()){
				al.remove(i%al.size());
				i=0;	
			}
			else if(i==14){
				al.remove(i);
				i=0;
			}
			i++;
		}
		System.out.println(al.get(0));
	*/
		   int n = 100;
		   boolean[] arr = new boolean[n];
		   for(int i=0; i<arr.length; i++) {
		    arr[i] = true;//下标为TRUE时说明还在圈里
		   }
		   int leftCount = n;
		   int countNum = 0;
		   int index = 0;
		   while(leftCount > 1) {
		    if(arr[index] == true) {//当在圈里时
		     countNum ++; //报数递加
		     if(countNum == 14) {//报道14时
		      countNum =0;//从零开始继续报数
		      arr[index] = false;//此人退出圈子
		      leftCount --;//剩余人数减一
		     }
		    }
		    index ++;//每报一次数,下标加一
		    if(index == n) {//是循环数数,当下标大于n时,说明已经数了一圈,
		     index = 0;//将下标设为零重新开始。
		    }
		   }
		   for(int i=0; i<n; i++) {
		    if(arr[i] == true) {
		     System.out.println(i);
		    }
		   }
	}

}














  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值