繁体   English   中英

有人可以帮我修复此代码(字符串)-java

[英]can someone help me fix this code(string)-java

我试图写一个老仆人。 在处理完卡片并进行排序后,我将卡片分为两部分,一个是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♢'

还是有另一种方法,因为当一对移开时,有两个空的空间,所以...我已经挣扎了很长时间……

如果要比较两个字符串,可以使用“等于”,例如

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.

}

要比较第一个字符,请更改此行

 if (q == p) {

 if (q.charAt(0) == p.charAt(0)) {

请注意, q == p检查qp引用相同的字符串 ,并且根本不查看内容。 如果q.equals(p)内容比较完整字符串(或任何其他非char,int等等的对象),则应使用equalsq.equals(p)仅在两个内容相同时才返回true。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM