我试着写一个老女仆。 交易卡和排序后,我有两个部分的卡,一个是playerDeck,一个是computerDeck。现在这些对需要被删除。但是我在这个阶段被困住了。
例如(仅举例) playerDeck: 'A♡','A♢','8♡','8♢','8♠','Q♠','2♠','4♣','7♢','7♣', 'K♣','A♡','J♡','9♣','3♢'
computerDeck: '3♡','3♣','10♡','10♠','10♣','6♡','K♡','K♢','A♣','A♠', '4♢','7♡','7♠'
String q;
String p;
ArrayStringsTools AA=new ArrayStringsTools();//this is a class that i will use for removing item
for(int i=0;i<playerDeck.length-1;i++){
q=playerDeck[i];
q=q.substring(0,1);//i try to find the first character
p=playerDeck[i+1];//after finding first character, i can compare them,and if they are same, then i can remove them
p=p.substring(0,1);
if(q==p){
AA.removeItemByIndex(playerDeck,26,i);//this is the method that i used for removing same item,i will put this code below
AA.removeItemByIndex(playerDeck,26,i+1);//there are 51 cards in total,player has 26, computer has 25
}
}
public static int removeItemByIndex(String[] arrayOfStrings, int currentSize, int itemToRemove){//this is the method i used for removing item(first is the array of Deck, second is the size of Deck,third is the index of item to remove)
if( arrayOfStrings == null || currentSize > arrayOfStrings.length) {
System.out.println("ArrayStringsTools.removeItemByIndex: wrong call");
return currentSize;
}
if( itemToRemove < 0 || itemToRemove >= currentSize ) {
System.out.println("ArrayStringsTools.removeItem: item "
+ itemToRemove + " out of bounds. Array Unchanged.");
return currentSize;
}
int i;
for( i = itemToRemove; i < currentSize-1; i++){
arrayOfStrings[i] = arrayOfStrings[i+1];
}
arrayOfStrings[i]= null;
return currentSize-1;
我认为我写的正确,但它与原点相比并没有显示出任何差异。 结果应该是: playerDeck:'8♠','Q♠','2♠','4♣','K♣','A♡','J♡','9♣','3♢' computerDeck:'10♣','6♡','4♢'
还是有另一种方法可以做到这一点,因为当一对被移除时,有两个空的空间,所以...我已经挣扎了很长时间......
答案 0 :(得分:0)
如果你想比较两个字符串,你可以使用&#39; equals&#39;,比如
if(q.equals(p)){//q==p if true,they are save in the same location-this may not be what you want,and in this code it will be false forever.
}
答案 1 :(得分:0)
要比较第一个字符,请更改此行
if (q == p) {
到
if (q.charAt(0) == p.charAt(0)) {
请注意,q == p
会检查q
和p
是否引用相同字符串,并且根本不查看内容。如果要按内容比较完整字符串(或任何其他不是char,int等的对象),则应使用equals
:q.equals(p)
仅在两者具有相同的情况下才返回true内容。