Java练习合集1

  • Post author:
  • Post category:java




Java练习合集1



1、实现单例模式(两种)

public class Dog {
	private static Dog dog = null;
	private Dog(){
		
	}
	
	public static Dog getDog(){
		dog = new Dog();
		return dog;
	}

}


public class Dog {
	private static final Dog dog = new Dog();
	private Dog(){
		
	}
	
	public static Dog getDog(){
		return dog;
	}

}



2、简述Collections和Collection的区别

Collection是一个集合接口,没有实现类,用于引用子接口的对象。

Collections是一个工具类,包含各种有关集合的静态多态方法,不能实例化。



3、简述Java集合框架体系

集合有单列集合Collection和双列集合Map两个接口

Collection有List和Set两个接口

List有ArrayList、LinkedList、Vector三个实现类

Set有HashSet、TreeSet两个实现类。LinkedHashSet继承自HashSet

Map有Hashable、HashMap、TreeMap三个实现类

Properties继承自Hashable,LinkedHashMap继承自HashMap。



4、写出HashMap常见的遍历方式(两种)

public static void main(String[] args) {
		HashMap<String, String> hashMap = new HashMap<>();
		hashMap.put("四川", "成都");
		hashMap.put("贵州", "贵阳");
		hashMap.put("云南", "南宁");
		hashMap.put("广东", "广州");
		//使用KeySet
	    //将key转成Set集合,通过迭代器取出Set集合中的每一个key,再通过key获取相应的value
		Set<String> keySet = hashMap.keySet();
		Iterator<String> iterator = keySet.iterator();
		while(iterator.hasNext()){
			String key = iterator.next();
			String value = hashMap.get(key);
			System.out.println("key="+key+" value="+value);
		}
		System.out.println("----------------------");
		//这种方式一般不使用。
		//将key.value转成Set集合(entrySet()),通过迭代器取出Set集合中的每一个entrySet.
		Set<Entry<String,String>> entrySet = hashMap.entrySet();
		Iterator<Entry<String, String>> iterator2 = entrySet.iterator();
		while(iterator2.hasNext()){
			Entry<String, String> entry = iterator2.next();
			String key = entry.getKey();
			String value = entry.getValue();
			System.out.println("key="+key+" value="+value);
		}
		

	}



5、利用冒泡算法对byte类型数组排序

public class Test03 {

	public static void main(String[] args) {
		byte[] arr = {2,6,4,8,7};
		for(int i=1;i<arr.length;i++){
			for(int j=0;j<arr.length-i;j++){
				if(arr[j]>arr[j+1]){
					byte temp = arr[j];
					arr[j] = arr[j+1];
					arr[j+1] = temp;
				}
			}
		}
		for(byte i:arr){
			System.out.println(i);
		}

	}

}



6、结合二分查找法在数组{1,3,2,4,5,7,6}中找出数字3

public class Test04 {

	public static void main(String[] args) {
		int[] arr = new int[]{1,3,2,4,5,7,6};
		Arrays.sort(arr);//排序
		for(int i:arr){
			System.out.print(i+" ");
		}
		System.out.println();
		
		int choose = Test04.choose(arr, 3);
		System.out.println(choose);
		

	}
	
	public  static  int choose(int[] arr ,int value ){
		int min = 0;
		int max = arr.length-1;
		int mid = (min + max)/2;
		while(arr[mid]!=value){
			if(max>min){
				if(value<arr[mid]){
					max = mid - 1;
					mid = (max + min)/2;
				}else if(value>arr[mid]){
					min = mid +1;
					mid = (max + min)/2;
				}
			}else{
				return -1;
			}
			
		}
		return mid;
	}

}



7、计算斐波拉西数列中第n项的值

public class Test05 {

	public static void main(String[] args) {
		int fib = Test05.fib(8);
		System.out.println(fib);

	}
	
	public static int fib(int n){
		if(n>0){
			if(n==1){
				return 1;
			}
			if(n==2){
				return 1;
			}
			return fib(n-2)+fib(n-1);
		}else{
			return -1;
		}
	}

}



8、利用简单排序算法对int类型数组进行排序

public class Test06 {

	public static void main(String[] args) {
		int[] arr = new int[]{1,4,2,5,7,3};
		for(int i=0;i<arr.length-1;i++){
			for(int j=i+1;j<arr.length;j++){
				if(arr[i]>arr[j]){
					int temp = arr[i];
					arr[i] = arr[j];
					arr[j] = temp;
				}
			}
		}
		for(int i:arr){
			System.out.println(i);
		}

	}

}



9、请判断某个字符串是否是回文。

回文释义:如果一个字符串,从前向后读和从后向前读,都是一个字符串,称为回文;比如mom,dad,noon。

public class Test07 {

	public static void main(String[] args) {
		String s = "aasdffdssa";
		System.out.println(s);
		boolean b = true;
		for(int i=0,j=s.length()-1;i<s.length()/2;i++){
			String substring1 = s.substring(i, i+1);
			String substring2 = s.substring(j, j+1);
			if(substring1.equals(substring2)){		
				
			}else{
				b = false;
				break;
			}
			j--;
		}
		if(b){
			System.out.println("是回文");
		}else{
			System.out.println("不是回文");
		}
		
		


	}

}



10、请校验字符串类型的密码是否合法。合法的要求如下:

1、必须至少9个字符。

2、必须至少2个大写字符。

3、必须包含小写字母

4、必须包含阿拉伯数字

public class Test08 {

	public static void main(String[] args) {
		String s = "AAffaaaaaaa2";
		char[] charArray = s.toCharArray();
		int bigCount = 0;
		boolean small = false;//判断小写字符
		boolean a = false;// 判断阿拉伯数字
		boolean S = false;// 判断是否九个字符
		boolean big = false;//判断大写字符
		for (int i = 0; i < charArray.length; i++) {
			if (charArray.length > 9) {
				S = true;
			}
			
			if (charArray[i] >= 'A' && charArray[i] <= 'Z') {
				bigCount++;
				if (bigCount >= 2) {
					big = true;
				}

			}
			
			if (charArray[i] >= 'a' && charArray[i] <= 'z') {
				small = true;			

			}
			if (charArray[i] >= '0' && charArray[i] < '9') {
				a = true;				
			}

		}
		if(small&big&&S&&a){
			System.out.println("密码合法");
		}
		if (!a) {
			System.out.println("必须包含阿拉伯数字");
		}
		if (!S) {
			System.out.println("必须包含九个字符");
		}
		if (!big) {
			System.out.println("必须包含两个大写字符");
		}
		if (!small) {
			System.out.println("必须包含小写字符");
		}

	}

}



11、请利用泛型设计方法,用于实现任意引用类型数组指定位置元素交换

public class Test09<T> {

	public static void main(String[] args) {
		Test09 test09 = new Test09<>();
		Integer[] arr1 = {1,2,3,4,5};
		String[] arr2 = {"a","b","c","d"};
		test09.swap(arr1, 0, 3);
		for(Integer i:arr1){
			System.out.println(i);
		}
		test09.swap(arr2, 0, 2);
		System.out.println(Arrays.toString(arr2));
		
	}
	
	public T[] swap(T[] arr,int index1,int index2){
		T temp = arr[index1];
		arr[index1] = arr[index2];
		arr[index2] = temp;
		return arr;
		
	} 

}



12、请模拟用户登录;要求如下:

1、定义用户类,属性为用户名和密码。

2、使用集合存储多个用户对象

3、集合中用户不能重复

4、假设正确的用户名和密码为:zxx与9527或者zmy9528

5、对比用户信息,匹配成功则登录成功,否则登录失败

6、当用户名匹配失败时,提示没有该用户

7、当密码匹配失败时,提示密码有误

public class Test10 {

	public static void main(String[] args) {
		User user1 = new User("zxx","9528");
		User user2 = new User("zvv","9527");
		User user3 = new User("zxx","9527");
		HashSet<User> hashSet =new  HashSet<User>();
		hashSet.add(user1);
		hashSet.add(user2);
		hashSet.add(user3);
		Test10.match(user1);
		Test10.match(user2);
		Test10.match(user3);

	}
	
	
	public static void match(User user){
		String name = user.getUserName();
		String passWord = user.getPassWord();
		boolean account1 = false;//判断是否为zxx
		boolean account2 = false;//判断是否为zmy
		boolean code1 = false;//判断密码是否为9527
		boolean code2 = false;//判断密码是否为9528
		if(name.equals("zxx") ){
			account1 = true;
		}
		if(name.equals("zmy")){
			account2 = true;
		}
		if(passWord.equals("9527")){
			code1 = true;
		}
		if(passWord.equals("9528")){
			code2 = true;
		}
		
		if((account1&&code1)||(account2&&code2)){
			System.out.println("登陆成功");
		}
		if(!account1&&!account2){
			System.out.println("没有该用户");
		}
		
		if((account1&&!code1)||(account2&&!code2)){
			System.out.println("密码有误");
		}
		
	}

}



13、将表示当前时间的时间戳格式化为以下格式:2020年7月21 21:23:32

public class Test11 {

	public static void main(String[] args) {
		Date date = new Date();
		Locale locale = Locale.getDefault();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd HH:mm:ss ",locale);
		String format = dateFormat.format(date);
		System.out.println(format);

	}

}



14、生成一个随机0-100的小数,并转换为保留两位小数的字符串

public class Test12 {

	public static void main(String[] args) {
		Random random = new Random();
		double nextDouble = random.nextDouble()*100;
		System.out.println(nextDouble);
		
		String string1 = Double.toString(nextDouble);
		Integer string2 = new Integer(1);
		
		BigDecimal b1 = new BigDecimal(string1);
		BigDecimal b2 = new BigDecimal(string2);
		BigDecimal divide = b1.divide(b2,2,RoundingMode.HALF_UP);
		System.out.println(divide);
		
		
	}

}



15、请逆置字符串,例如:abc  —> cba

public static void main(String[] args) {
		String s= "abc";
		char[] charArray = s.toCharArray();
		for(int i=0,j=charArray.length-1;i<charArray.length/2;i++){
			char s2 = charArray[i];
			charArray[i] = charArray[j];
			charArray[j] = s2; 
			j--;
		}
		for(char i:charArray){
			System.out.println(i);
		}

	}

}



16、请对学生的成绩做降序排序。假若成绩相同则在成绩排序的基础上按照年龄由小到大排序。

学生类

ublic class Student implements Comparable<Student> {
	private String name;
	private double score;
	private int age;
	public Student() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Student(String name, double score, int age) {
		super();
		this.name = name;
		this.score = score;
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public double getScore() {
		return score;
	}
	public void setScore(double score) {
		this.score = score;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + age;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		long temp;
		temp = Double.doubleToLongBits(score);
		result = prime * result + (int) (temp ^ (temp >>> 32));
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Student other = (Student) obj;
		if (age != other.age)
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		if (Double.doubleToLongBits(score) != Double.doubleToLongBits(other.score))
			return false;
		return true;
	}
	@Override
	public String toString() {
		return "Student [name=" + name + ", score=" + score + ", age=" + age + "]";
	}
	
	//重写comparable方法
	@Override
	public int compareTo(Student o) {
		if(this.score>o.score){
			return -1;
		}else if(this.score<o.score){
			return 1;
		}else {
			if(this.age>o.age){
				return 1;
			}else if(this.age<o.age){
				return -1;
			}else{
				return this.name.compareTo(o.name);
			}
		}
	}
	

}

测试类

public class Test14 {

	public static void main(String[] args) {
		Student s1 = new Student("zxx",56,18);
		Student s2 = new Student("jhg",80,18);
		Student s3 = new Student("zs",56,19);
		Student s4 = new Student("zw",90,20);
		TreeSet<Student> set = new TreeSet<>();
		set.add(s1);
		set.add(s2);
		set.add(s3);
		set.add(s4);
		
		Iterator<Student> iterator = set.iterator();
		while(iterator.hasNext()){
			Student student = iterator.next();
			System.out.println(student);
			
		}
		

	}

}



17、请统计字符串”Your future depends on your dreams so go to sleep”中各个字母出现的次数。例如:字母o出现了6次

public class Test15 {

	public static void main(String[] args) {
		String s = "Your future depends on your dreams so go to sleep";
		HashMap<String, Integer> hashMap = new HashMap<>();
		
		for(int i=0;i<s.length();i++){
			String key = s.substring(i, i+1);
            //判断字母是否出现过
			boolean containsKey = hashMap.containsKey(key);
			if(containsKey){
				Integer count = hashMap.get(key);
				count++;
				hashMap.put(key, count);
			}else{
				hashMap.put(key, 1);
			}
		}
		//遍历
		Set<String> keySet = hashMap.keySet();
		Iterator<String> iterator = keySet.iterator();
		while(iterator.hasNext()){
			String key = iterator.next();
			Integer value = hashMap.get(key);
			System.out.println(key+"出现了"+value+"次");
			
		}
		
	}
		
		

	}



18、请添加你喜欢的歌手们以及该歌手唱过的歌曲。

歌手类

public class Singer {
	private String name;
	private ArrayList<Song> song;
	public Singer() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Singer(String name, ArrayList<Song> song) {
		super();
		this.name = name;
		this.song = song;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public ArrayList<Song> getSong() {
		return song;
	}
	public void setSong(ArrayList<Song> song) {
		this.song = song;
	}
	@Override
	public String toString() {
		return  name + ": 作品:" + song ;
	}
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		result = prime * result + ((song == null) ? 0 : song.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Singer other = (Singer) obj;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		if (song == null) {
			if (other.song != null)
				return false;
		} else if (!song.equals(other.song))
			return false;
		return true;
	}
	
	
	
	
	

}

歌曲类

public class Song {
	private String name;

	public Song() {
		super();
		// TODO Auto-generated constructor stub
	}

	public Song(String name) {
		super();
		this.name = name;
	}

	public String getName() {
		return name;
	}

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

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Song other = (Song) obj;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}

	@Override
	public String toString() {
		return   name ;
	}
	

	
	

}

测试类

public class Test16 {

	public static void main(String[] args) {
		Song song1 = new Song("单车");
		Song song2 = new Song("浮夸");
		Song song3 = new Song("最佳损友");
		ArrayList<Song> arrayList1 = new ArrayList<>();
		arrayList1.add(song1);
		arrayList1.add(song2);
		arrayList1.add(song3);
		Singer singer1 = new Singer("陈奕迅",arrayList1);
		System.out.println(singer1);
		
		Song song4 = new Song("龙卷风");
		Song song5 = new Song("夜曲");
		Song song6 = new Song("稻香");
		ArrayList<Song> arrayList2 = new ArrayList<>();
		arrayList2.add(song4);
		arrayList2.add(song5);
		arrayList2.add(song6);
		Singer singer2 = new Singer("周杰伦",arrayList2);
		System.out.println(singer2);
		
		

	}

}



版权声明:本文为weixin_48291026原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。