首页 > 解决方案 > 如何使用限制 = n 的递归 java 打印奇数

问题描述

我是编程语言的新手。

我有以下代码

import javax.swing.*;

public class oddTest{

public static void odd(int a){
    if (a < 0){
        if (a % 2 != 0){
        a++;
        }
    }
    odd(--a);
}

public static void main(String[] args){
    int n = 0;
    String str = JOptionPane.showInputDialog(null, "make the limits = ");
    n = Integer.parseInt(str);
    odd(n);
    JOptionPane.showInputDialog(n);
}
}

如果我做的限制是7,输出应该是:

输出:1、3、5、7

标签: javarecursion

解决方案


你可以这样使用:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class OddCalc {

    public static void main(String[] args) {

        List<Integer> odds = OddCalc.odd(7);
        Collections.reverse(odds);
        System.out.println(odds);

    }

    public static List<Integer> odd(int a) {
        return odd(a, new ArrayList<Integer>());
    }

    private static List<Integer> odd(int a, List<Integer> odds) {

        if( a == 0 ) {
            return odds;
        }

        if( a % 2 != 0 ) {
            odds.add(a);
        }

        return odd(--a, odds);
    }
}

输出将是[1, 3, 5, 7],您可以将结果放入您的JPanel.


推荐阅读