簡體   English   中英

使用靜態數組在 Java 中使用 3 種方法(Addition、numberEven、numberOdd)

[英]Use 3 methods (Addition, numberEven, numberOdd) in Java with a static array

我有一個名為tab的數組,其中包含多個數字

int[] tab = {1,3,4,2};

我必須創建 3 種方法:

1)第一個addition()方法

2) 第二個evenNumber()方法

3)第三個evenOdd()方法

通過使用我的 3 種方法,我可以在下面顯示 2 個結果:

# 1 - Calculate the sum of all even numbers in the table 
# 2 - Calculate the sum of all odd numbers in the table 

我找到了檢索所有偶數的方法,然后將偶數相加,結果為6

關於奇數,結果應該是4 ,我檢索0 ???

在此處輸入圖片說明

我不明白我的問題。

這是我的代碼的一個想法:

public static void main(String[] args) {
        // TODO code application logic here

        int[] tab = {1,3,4,2};

        int length = tab.length;

        length = evenNumber(tab, length);
        int evenSum = addition(tab, length);


        length = oddNumber(tab, length);
        int oddSum = addition(tab, length);


        System.out.println("# 1 - Calculate the sum of all even numbers in the table -> " + evenSum);
        System.out.println("# 2 - Calculate the sum of all odd numbers in the table -> " + oddSum);



    }

    public static int addition(int tab[], int length){
        int sum = 0;
        for(int i=0; i<length; i++){
            sum += tab[i];
        }
        return sum;
    }

    public static int evenNumber(int tab[], int length){
        int n = 0;
        for(int i=0; i<length; i++){
            if(tab[i] % 2 == 0){
                tab[n++] = tab[i];
            }
        }
        return n;

    }

   public static int oddNumber(int[] tab, int length) {
        int n=0;
        for(int i=0; i<length;i++){
            if(tab[i] % 2 == 1 ){ 
               tab[n++] = tab[i];
            }
        }
       return n;
    }

感謝您的幫助。

您的問題是您正在拖動長度並將其傳遞給所有方法並返回它(為什么?)。 另外,我認為您沒有按照方法的名稱進行操作。

你想做的是這樣的事情(我猜這是作業):

    public static void main(String[] args) {
        // TODO code application logic here

        // Input array with all the numbers
        int[] tab = {1,3,4,2};

        // Calculate even and odd sums
        int[] sums = calculateSums(tab);

        // Extract results
        int evenSum = sums[0];
        int oddSum  = sums[1];

        // Print the results
        System.out.println("# 1 - Calculate the sum of all even numbers in the table -> " + evenSum);
        System.out.println("# 2 - Calculate the sum of all odd numbers in the table -> " + oddSum);
    }

    public static int[] calculateSums(int[] tab) {
        // Initialize even and odd sums to zero
        int[] sums = {0, 0};

        // Loop through the array to check the numbers one by one
        for(int i = 0; i < tab.length; i++) {
            int n = tab[i]; // n is the current number

            if (evenNumber(n)) {
                // Add to evenSum if it's even
                sums[0] += n;
            }

            if (oddNumber(n)) {
                // Add to oddSum if it's odd
                sums[1] += n;
            }
        }
        return sums;
    }

    // Receives an array of integers and returns the total sum
    public static int addition(int tab[]){
        int sum = 0;
        for(int i = 0; i < tab.length; i++){
            sum += tab[i];
        }
        return sum;
    }

    // Checks if a number is even
    public static boolean evenNumber(int number){
        return number % 2 == 0;

    }

    // Checks if a number is odd
    public static boolean oddNumber(int number) {
        return !evenNumber(number);
    }

如果您運行該程序,它將打印:

# 1 - Calculate the sum of all even numbers in the table -> 6
# 2 - Calculate the sum of all odd numbers in the table -> 4

您鍛煉所需的方法:

  • addition() :獲取一個數字數組並返回總和
  • evenNumber() :取一個數字,如果數字是偶數則返回真
  • oddNumber() :取一個數字,如果數字是奇數則返回真

如果你考慮一下,在for循環中你甚至不需要同時使用evenNumberoddNumber因為如果一個數字不是偶數,它必須是奇數,反之亦然。 一個簡單的if-else就足夠了,這也是我使用另一個實現一個的原因( oddNumber調用evenNumber )。

嘗試這樣做,看看您是否仍然獲得所需的結果。 請確保您真的了解您的代碼在做什么,並在這里詢問您的要求是否有問題(我不得不猜測一下)。

由於您問題的學習性質,我對代碼的評論太多了。

我認為這對你有用:
addallNumbers()執行它所說的,並且addEvenOrOddNumbers()如果even標志設置為true ,則添加所有偶數,或者如果設置為false添加所有奇數。

public class Main {
    // This adds all numbers.
    public static int addAllNumbers(int[] arr){
        int sum = 0;
        int length = arr.length;
        for(int i = 0; i < length; ++i){
            sum += arr[i];
        }
        return sum;
    }
    // This adds all odd or even numbers, based on the value of even.
    public static int addEvenOrOddNumbers(int[] arr, boolean even){
        int parity = 0;
        if (!even){
            parity = 1;
        }
        int sum = 0;
        int length = arr.length;
        for(int i = 0; i < length; ++i){
            if (arr[i] % 2 == parity) {
                sum += arr[i];
            }
        }
        return sum;
    }
    public static void main(String[] args) {
        int[] tab = {1,3,4,2};

        System.out.println("Added all numbers, Result: " + addAllNumbers(tab));
        System.out.println("Added all even numbers, Result: " + addEvenOrOddNumbers(tab, true));
        System.out.println("Added all odd numbers, Result: " + addEvenOrOddNumbers(tab, false));
    }
}

運行此輸出時:

Added all numbers, Result: 10
Added all even numbers, Result: 6
Added all odd numbers, Result: 4

你為什么不做這樣的事情

public class Test {
public static void main(String[] args) {
    int[] tab = {1,3,4,2};
    System.out.println("Sum of even numbers = " + sumEvens(tab)); // return sum printed 
    System.out.println("Sum of odd numbers = " + sumOdds(tab));
    System.out.println("Total sum " + totalSum(tab));
}
public static int sumEvens(int[] tab) {
    int sum = 0;
  for(int i = 0 ; i < tab.length ; ++i) {
      if(tab[i] % 2 == 0) sum+=tab[i];
  }
     return sum;
}
public static int sumOdds(int[] tab) { // returns sum of odds
    int sum = 0;
    for(int i = 0 ; i < tab.length ; ++i) {
        if(tab[i] % 2 != 0) sum+=tab[i];
    }
    return sum;
}
public static int totalSum(int[] tab) { 
    return sumEvens(tab) + sumOdds(tab);// total sum is equal to sum of even and odd sums
}   

}

暫無
暫無

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

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