Skip to content
Advertisement

How to print odd numbers using recursive java with the limits = n

I’m a newbie of programming languages.

I have the following code

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

if i make the limits is 7, the output should be :

the output : 1, 3, 5, 7

Advertisement

Answer

import com.sun.deploy.util.StringUtils;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;

public class Main {

    static List<String> odds = new ArrayList<>();

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

    static void printOdds(int n) {
        if (n < 1) return;
        if (n%2 == 0) n--;
        printOdds(n-2);
        odds.add(String.valueOf(n));
    }
}

You can use below code:

import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;

public class Main {

    static List<String> odds = new ArrayList<>();

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

        StringBuilder nameBuilder = new StringBuilder();
        for (String oddNum : odds) {
            nameBuilder.append(oddNum).append(",");
        }
        nameBuilder.deleteCharAt(nameBuilder.length() - 1);

        JOptionPane.showMessageDialog(null, nameBuilder.toString());
    }

    static void printOdds(int n) {
        if (n < 1) return;
        if (n%2 == 0) n--;
        printOdds(n-2);
        odds.add(String.valueOf(n));
    }
}

if you dont have any library other than jdk.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement