不知道怎么称呼我的话。
public NaturalNumberTuple(int[] numbers) {
int [] thisTuple = new int[numbers.length];
int count = 0;
for(int j = 0; j < numbers.length; j++){
if(numbers[j] > 0){
thisTuple[j] = numbers[j];
count++;
}
}
int[] newTuple = new int[count];
for(int i = 0; i < newTuple.length; i++){
int k = i;
while(thisTuple[k] <= 0){
k++;
}
newTuple[i] = thisTuple[k];
}
this.tuple = newTuple;
}
这是我创建新NaturalNumberTuple的代码片段。
所以这是我想要使用的数组:int [] tT2 = {1,2,4,-4,5,4,4}; 我只想使用大于0的自然数,我的问题不是剪掉负数,而是我的控制台给我这个:元组(数字:1,2,4,5,5,4)。 问题是如果我跳过那个带有我的while循环的负值来获得更高的值(k)我将不得不在我的for循环中传递相同的(k),因为我已经得到了它我的阵列。我希望你理解我的问题。 抱歉英文不好..
编辑:不能使用java本身的任何方法,如System.arrayCopy
答案 0 :(得分:0)
第一个循环中有错误。修复它使第二个循环更简单:
public NaturalNumberTuple(int[] numbers) {
int [] thisTuple = new int[numbers.length];
int count = 0;
for(int j = 0; j < numbers.length; j++){
if(numbers[j] > 0){
thisTuple[count] = numbers[j]; // changed thisTuple[j] to thisTuple[count]
count++;
}
}
int[] newTuple = new int[count];
for(int i = 0; i < newTuple.length; i++) {
newTuple[i] = thisTuple[i];
}
this.tuple = newTuple;
}
当然,第二个循环可以替换为System.arrayCopy
的调用。
答案 1 :(得分:0)
如果只是重新启动for循环,我会将你的while循环改为。从这里说:
while(thisTuple[k] <= 0){
k++;
}
对于这样的事情:
if (thisTuple[k] <= 0)
continue;
当您遇到负数或零数时,这会阻止您添加相同的数字。
答案 2 :(得分:0)
此代码将解决您的问题。代码将在以下链接Tuple Exampple
中进行检查 int [] thisTuple = new int[numbers.length];
int count = 0;
for(int j = 0; j < numbers.length; j++){
if(numbers[j] > 0){
thisTuple[count] = numbers[j]; //Change to thisTuple[count]
count++;
}
}
int[] newTuple = new int[count];
for(int i = 0; i < count; i++){
newTuple[i] = thisTuple[i];
}