簡體   English   中英

如何在循環中跳過特定數字

[英]How to jump over a specific number in a loop

不知道如何調用我的線程。

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的自然數,而我的問題不是要消除負數,而是我的控制台給了我這個數:Tuple(Numbers:1,2,4,5,5,4)。 問題是如果我跳過while循環中的負值以獲得更高的(k),我將不得不在我不想的for循環中傳遞相同的(k),因為我已經在其中獲取了我的數組。 希望你能理解我的問題。 對不起,英語不好。

編輯:不能使用Java本身的任何方法,例如System.arrayCopy

您在第一個循環中有一個錯誤。 修復它使第二個循環更加簡單:

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的調用。

我會將while循環更改為if,只需重新啟動for循環即可。 這樣說:

while(thisTuple[k] <= 0){
    k++;
}

對於這樣的事情:

if (thisTuple[k] <= 0)
    continue;

當您遇到負數或零數時,這可以阻止您兩次添加相同的數。

此代碼將解決您的問題。 在以下鏈接中檢查代碼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];
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM