abu-Ahmed al-khatiri:
Soy un novato de los lenguajes de programación.
Tengo el siguiente código
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);
}
}
si hago los límites es 7
, la salida debe ser:
la salida: 1, 3, 5, 7
Serhat Oz:
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));
}
}
Se puede utilizar por debajo de código:
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));
}
}
Si usted no tiene ninguna otra biblioteca de JDK.