不知道怎么叫我的线。
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};我只想使用大于0的自然数,我的问题不是删除负数,而是我的控制台给了我一个元组(数字:1,2,4,5,5,4)。问题是,如果我跳过那个值,这与我的while循环是负的,为了得到更高的(k),我必须在for循环中传递相同的(k),这是我不想要的,因为我已经在数组中得到了它。希望你能理解我的问题。对不起英语不好..。
编辑:不能使用java本身的任何方法,比如System.arrayCopy
发布于 2014-11-30 10:50:15
在第一个循环中有一个错误。修复它使第二个循环变得更简单:
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的调用。
发布于 2014-11-30 10:55:36
如果这只是重新启动for循环,我会将您的while循环更改为a。从这一点上说:
while(thisTuple[k] <= 0){
k++;
}像这样的事情:
if (thisTuple[k] <= 0)
continue;这将阻止您在遇到负数或零数时两次添加相同的数字。
发布于 2014-11-30 11:04:45
这段代码会解决你的问题。代码在下面的链接[医]元组中签入
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];
}https://stackoverflow.com/questions/27212389
复制相似问题