我已经获得了这个数组,可以在一个类中用于作业。
/**
* compactHand - THIS METHOD IS SUPPLIED FOR YOU!
* re-order the array so that all cards occupy the early indices, i.e. 0,1,2,...
* and that all the nulls are in the higher indices.
* Also count the number of cards in the array and set ncard accordingly.
* Example: if array is [Kclub][null][2diamond][null][7spade]
* then this routine sets array to [Kclub][2diamond][7spade][null][null] and sets ncard to 3.
* Note that the relative order of cards is not changed.
*/
private void compactHand(){
int nc=0, ix=0, nullix=-1;
// find first null
do{
if (cards[ix]==null){
nullix = ix;
break;
}
} while (++ix<cards.length);
if (nullix==-1){
// there were no nulls. set ncards and return.
ncard = cards.length;
return;
}
nc = nullix;
// loop to end of array and swap cards for nulls
for(ix=nullix; ix<cards.length; ix++)
if (!(cards[ix]==null)){
cards[nullix++] = cards[ix];
cards[ix] = null;
nc++;
}
ncard = nc;
}
我已经完成了大部分任务,但是对于其中一种方法,我需要在名为cards的数组中调用它。我尝试使用以下方式调用它:
cards.compactHand();
该方法不接受数组作为参数,但在我需要完成的方法中,指令明确指出要使用它。
/**
* delete Cards at specified indices and compact the array.
* if any indices do not correspond to cards then the array must be unchanged
* and this member returns false.
* otherwise the specified cards are deleted, the array compacted and true returned.
* @param index index of array element to delete
* @return true if all elements successfully deleted, false if none deleted.
*/
该方法被标记为私有,但我可以访问它,因为它在同一个类中。
对此有任何帮助将不胜感激。
答案 0 :(得分:0)
cards
数组应该是类中的实例变量。实例变量在类的方法之外声明,通常在它的开头。然后可以从该类的任何方法调用它们。 This answer有一些关于实例变量的例子。
答案 1 :(得分:0)
应该有另一个方法返回一个可以调用方法compactHand();
的数组,否则这个方法不返回数组。
我已经声明了一些数组是一个构造函数,这可能有帮助
public class Test {
private String[] cards;
private int ncard;
public Test(String[] cards) {
this.cards = new String[cards.length];
for(int i = 0; i <cards.length; i++){
this.cards[i] = cards[i];
}
}
private void compactHand() {
int nc = 0, ix = 0, nullix = -1;
// find first null
do {
if (cards[ix] == null) {
nullix = ix;
break;
}
} while (++ix < cards.length);
if (nullix == -1) {
// there were no nulls. set ncards and return.
ncard = cards.length;
return;
}
nc = nullix;
// loop to end of array and swap cards for nulls
for (ix = nullix; ix < cards.length; ix++)
if (!(cards[ix] == null)) {
cards[nullix++] = cards[ix];
cards[ix] = null;
nc++;
}
ncard = nc;
}
public static void main(String[] args) {
String[] cards = {"1", "2", "king", "ace"};
Test test = new Test(cards);
test.compactHand();
for (int i = 0; i < cards.length; i++) {
System.out.println(Arrays.toString(cards));
}
}
}