2017-01-24 56 views
1

我试图写一个老女仆。 处理卡和分类后,我有两个部分的卡,一个是playerDeck,一个是computerDeck。现在这些对需要被删除,但我在这个阶段被卡住了。有人可以帮我修复此代码(字符串)-java

例如(只是一个例子) playerDeck: 'A♡', 'A♢', '8♡', '8♢', '8♠', 'Q♠', '2♠', '♣','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

playerDeck:'8♠','Q♠','2♠','4♣','K♣','A♡','J♡','9♣','3♢' computerDeck: '10♣','6♡','4♢' –

+0

将较长的一行分成较短的一行。阅读非常长的代码行是很痛苦的,因为如果你滚动查看一行的结尾,你就会忽视程序的其余部分。一个常见的限制是“不超过80个字符” – tucuxi

回答

0

要比较的第1个字符,改变这一行

if (q == p) { 

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

注意q == p检查,看是否qp相同的字符串,并在内容不看的。如果要按内容比较完整字符串(或任何其他非char,int等的对象),则应使用equalsq.equals(p)仅当两者具有相同内容时才返回true。

+0

现在它说'线程中的异常'主要“test.main(java.lang.NullPointerException)”(test.java.52)第52行是“p = p.substring(0,1);”最新错误 –

+0

'p'在那一点是'null'。 'null'引用不指向实际对象;并且尝试在空引用上调用'substring(0,1)'是错误的(因为没有实际的对象接收该调用)。至于*为什么*'p'为空,您可能忘记初始化它的值。当将'String'数组声明为'String a [] = new String [10]'时,数组中的所有10个'String'引用都开始指向'null'。 – tucuxi

0

如果要比较两个字符串,可以使用‘等于’,像

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. 

} 
+0

我只想比较第一个字符 –

+0

字符串不是原始类型,不像char,只能使用equals来测试字符串是否相等。 –

+2

@Joe用toCharArray进行转换,然后比较每个新数组的第一个元素 –

相关问题