无法弄清楚我在这个方法中做错了什么(compute_even)

时间:2014-07-05 23:29:52

标签: java methods computation

我在理解我应该如何在本练习中使用compute_even方法时遇到一些问题,希望有人可以帮助我。

没关系compute_odd方法我还在考虑那个!

以下是练习:

编写一个名为choose_function的void方法,其参数n的类型为int。如果n的值是偶数,则方法将调用方法compute_even传递给它的参数n的值,否则该方法将调用方法compute_odd传递给它的值为n。

这两种方法将在控制台上按以下顺序打印:

compute_even:2,4,8,16,32,64,128 ......直到n

compute_odd:1,3,6,10,15,21,28 ......直到n

编写程序,其中用户输入大于零的int数n1(因此程序将提示用户输入值,直到不满足条件)。 程序将在控制台上打印与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)
{

}

强文

2 个答案:

答案 0 :(得分:0)

问题出在这里。

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

此代码每次都会向调用者返回2。为什么?因为在你的循环中,你设置r = 1 * 2 = 2,然后立即返回r。你要做的是检查这个新的r是否等于他传递的参数。如果没有,则打印r和空格,然后继续循环。如果它相等,则打印最终数字并从方法返回。

int r = 1;
do
{
    r = r*2;
    System.out.print(r + " ");
    if (r == k) return r;
}while(r <= k);

答案 1 :(得分:0)

试用此代码

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;   
    }
}

单独尝试在compute_oddcompute_even方法中打印值。您的算法似乎也存在问题,

你应该使用

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

而不是使用

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

示例输出:

输入正整数值:

-5

输入正整数值:

5

1 3 5