Search code examples
javamethodscomputation

Can't figure out what I am doing wrong in this method ( compute_even )


I am having some problem understanding how I am supposed to do the compute_even method in this exercise, I hope someone can help me out.

Nevermind the compute_odd method I am still thinking about that one!

Here is the exercise:

Write a void method called choose_function that has a parameter n of type int. If the value of n is even the method will call the method compute_even passing to it value of the parameter n, else the method will call the method compute_odd passing to it the value of n.

The two methods will print on the console the following sequence:

compute_even: 2, 4, 8, 16, 32, 64, 128… up to n

compute_odd: 1, 3, 6, 10, 15, 21, 28 … up to n

Write program in which the user enter an int numbers n1 greater than zero (hence the program will prompt the user to enter a value until the condition is not satisfied). The program will print on the console the sequence associated to the value of n1.

public static void main(String[] args)
{
    Scanner input = new Scanner(System.in);
    int n1;
    do
    {
        System.out.println("Enter a positive integer value: ");
        n1 = input.nextInt();
    }while(n1 <= 0);

    choose_function(n1);

    input.close();
}

public static void choose_function(int n)
{
    if(n%2 == 0)
        System.out.print(compute_even(n));
    else
        System.out.print(compute_odd(n));
}

public static int compute_even(int k)
{
    int r = 1;
    do
    {
        r = r*2;
        return r;
    }while(r <= k);
}

public static int compute_odd(int k)
{

}

strong text


Solution

  • Try this Code

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int n1;
        do {
            System.out.println("Enter a positive integer value: ");
            n1 = input.nextInt();
        } while (n1 <= 0);
    
        choose_function(n1);
        System.out.println();
        input.close();
    }
    
    public static void choose_function(int n) {
        if (n % 2 == 0) {
            compute_even(n);
        } else {
            compute_odd(n);
        }
    }
    
    public static void compute_even(int k) {
        int r = 0;
        while (r <= k) {
        System.out.print(""+r+" ");
            r = r + 2;  
        } 
    }
    public static void compute_odd(int k) {
        int r = 1;
        while (r <= k){
            System.out.print(""+r+" ");
            r = r+2;   
        }
    }
    

    Try printing values inside compute_odd and compute_even method seperately. It seems there is a problem with your algorithm as well,

    You should use

    int r =0;
    r = r+2 // returns 0 2 4 6 8...
    

    instead of using

    int r = 1;
    r = r*2;  // This would return 2 4 8 16...
    

    Sample output :

    Enter a positive integer value:

    -5

    Enter a positive integer value:

    5

    1 3 5