按花色和牌大小排序,红桃>方块>黑桃>梅花。
大概思路:新建Card对象,属性有
private int id; //花色,1234对应红方黑梅
private int values; //数字1-13依次对应牌值12345678910JQK
分别对它们赋权值,values权值为本身,红桃权值13,方块26,黑桃39,梅花42,最后根据权值大小排序即可。
public class Card {
private int id; //花色,1234对应红方黑梅
private int values; //牌值12345678910JQK
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getValues() {
return values;
}
public void setValues(int values) {
this.values = values;
}
}
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class cardsSort2 {
public static void main(String[] args) {
List<Card> cards = new ArrayList<Card>(10);
String[] v = {"3","4","5","6","7","8","9","10","J","Q","K","A","2"};
for (int i = 0; i < 10; i++) {
Card card = new Card();
int a = ((int)(Math.random()*1000))%4+1;
card.setId(a);
int b = ((int)(Math.random()*1000))%13;
card.setValues(b);
cards.add(card);
}
System.out.println("排序前:");
Iterator<Card> cardsIter = cards.iterator();
while(cardsIter.hasNext()){
Card temp = cardsIter.next();
System.out.print(getId(temp.getId()));
System.out.print(v[temp.getValues()]);
System.out.print(",");
}
System.out.println();
System.out.println("排序后:");
//冒泡cards
for (int i = 0; i < cards.size()-1; i++) {
for (int j = 0; j < cards.size()-i-1; j++) {
if(getCardNum(cards.get(j))>getCardNum(cards.get(j+1))) {
Card temp = cards.get(j);
Card temp2 = cards.get(j+1);
cards.set(j, temp2);
cards.set(j+1, temp);
}
}
}
Iterator<Card> cardsIter2 = cards.iterator();
while(cardsIter2.hasNext()){
Card temp2 = cardsIter2.next();
System.out.print(getId(temp2.getId()));
System.out.print(v[temp2.getValues()]);
System.out.print(",");
}
}
public static int getCardNum(Card card) {
return getCardIdNum(card.getId()) + card.getValues();
}
public static int getCardIdNum(int id) {
if(id == 1 ) {
return 13;
}else if(id == 2) {
return 26;
}else if(id == 3) {
return 39;
}else if(id == 4) {
return 42;
}else{
return 0;
}
}
public static String getId(int id) {
if(id == 1 ) {
return "红桃";
}else if(id == 2) {
return "方块";
}else if(id == 3) {
return "黑桃";
}else if(id == 4) {
return "梅花";
}else{
return "";
}
}
}
代码有很多地方可优化,主要还是看思路吧,权值的赋予,冒泡的使用。