【问题标题】:Can't figure out what I am doing wrong in this method ( compute_even )无法弄清楚我在这种方法中做错了什么( compute_even )
【发布时间】:2014-08-26 19:16:13
【问题描述】:

我在理解本练习中应该如何执行 compute_even 方法时遇到了一些问题,希望有人能帮助我。

别在意 compute_odd 方法,我还在想那个!

这是练习:

编写一个名为 choose_function 的 void 方法,它有一个 int 类型的参数 n。如果 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

编写程序,让用户输入一个大于零的整数 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)
{

}

强文本

【问题讨论】:

  • 您需要打印从零到 n1 的所有偶数/奇数吗?

标签: java methods computation


【解决方案1】:

试试这个代码

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

【讨论】:

  • 非常感谢,这确实帮助我理解了它,但是如果您阅读练习,所要求的是以下序列“偶数”2、4、8、16、32、64、128 等。 ..感谢您的评论,我设法得到它!我刚刚用 2 替换了 r 起始值,而现在 r = r*2
【解决方案2】:

问题就在这里。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多