一、问题内容
1.有一个数组,储存着Cat 对象,每个Cat对象有很多成员变量,其中一个代表颜色colour,有两个值:白色和灰色,要求编一个函数,将数组中所有白猫都排在灰猫前面
2.如果猫的颜色有三种,白色、灰色、黑色,要求编一个函数,将白猫放在前面、灰猫放在中间、黑猫放在最后面
3.不仅按照白猫、灰猫、黑猫的顺序排序,而且每种颜色的猫原本内部顺序不能改变
二、实现代码
package test;
import java.util.Random;
public class CatHouse {
public static void main(String[] args){
String[] colour = new String[3];
colour[0] = "白";
colour[1] = "灰";
colour[2] = "黑";
Random ran = new Random();
Cat[] catArr = new Cat[10];
String[] catColour = new String[10];
// 1.第一组
System.out.println("1.两种颜色,白猫在前,灰猫在后");
for(int i = 0;i<catArr.length;i++){
catArr[i] = new Cat();
catArr[i].colour = colour[ran.nextInt(2)];
catArr[i].number = i+1;
}
for(int i=0;i<catColour.length;i++){
catColour[i]=catArr[i].colour;
}
System.out.println("排序前猫的颜色:"+showArray(catColour,","));
//开始排序,两种颜色,白猫在前,灰猫在后
for(int i = 0; i < catArr.length;i++){
for(int j = i; j < catArr.length; j++){
if ("白".equals(catArr[j].colour)){
Cat temp = catArr[i];
catArr[i] = catArr[j];
catArr[j] = temp;
break;
}
}
}
for(int i=0;i<catColour.length;i++){
catColour[i]=catArr[i].colour;
}
System.out.println("排序后猫的颜色:"+showArray(catColour,","));
System.out.println();
// 2.第二组
System.out.println("2.三种颜色,白、灰、黑顺序排序");
for(int i = 0;i<catArr.length;i++){
catArr[i] = new Cat();
catArr[i].colour = colour[ran.nextInt(3)];
catArr[i].number = i+1;
}
for(int i=0;i<catColour.length;i++){
catColour[i]=catArr[i].colour;
}
System.out.println("排序前猫的颜色:"+showArray(catColour,","));
//开始排序,三种颜色,白、灰、黑顺序
int CatCageNum = 0 ;
for(int i = 0; i < colour.length-1;i++){
for(int j = CatCageNum; j < catArr.length;j++){
for(int k = j; k < catArr.length; k++){
if (colour[i].equals(catArr[k].colour)){
Cat temp = catArr[j];
catArr[j] = catArr[k];
catArr[k] = temp;
CatCageNum ++;
break;
}
}
}
}
for(int i=0;i<catColour.length;i++){
catColour[i]=catArr[i].colour;
}
System.out.println("排序后猫的颜色:"+showArray(catColour,","));
System.out.println();
// 3.第三组
System.out.println("3.三种颜色,白、灰、黑顺序排序,且各颜色内部顺序不变");
for(int i = 0;i<catArr.length;i++){
catArr[i] = new Cat();
catArr[i].colour = colour[ran.nextInt(3)];
catArr[i].number = i+1;
}
for(int i=0;i<catColour.length;i++){
catColour[i]=catArr[i].colour+catArr[i].number;
}
System.out.println("排序前猫的颜色:"+showArray(catColour,","));
//开始排序,三种颜色,白、灰、黑顺序,且各颜色内部序号不变
CatCageNum = 0 ;
for(int i = 0; i < colour.length-1;i++){
for(int j = CatCageNum; j < catArr.length;j++){
for(int k = j; k < catArr.length; k++){
if (colour[i].equals(catArr[k].colour)){
for(int l = k; l > j; l--){
Cat temp = catArr[l];
catArr[l] = catArr[l-1];
catArr[l-1] = temp;
}
CatCageNum ++;
break;
}
}
}
}
for(int i=0;i<catColour.length;i++){
catColour[i]=catArr[i].colour+catArr[i].number;
}
System.out.println("排序后猫的颜色:"+showArray(catColour,","));
}
public static String showArray(String[] array,String str){
String result = "";
for(String i : array){
result = result + str + i;
}
return result.substring(1);
}
}