java - 如何使用限制 = 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
解决方案
你可以这样使用:
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
.
推荐阅读
- unity3d - 如何为预制件的孩子赋值
- node.js - 如何将 SSE 聊天节点 express 迁移到节点 hapi
- php - 从数据库列显示 json 结果有问题吗?
- .net - 更改 Docker 容器中的 inotify.max_user_instances 限制
- r - 如何结合 geom_smooth() 修复 x 和 y 轴?
- wordpress - 优化与 bluehost 的 wordpress 站点共享
- xamarin - 第一个应用显示来自第二个应用的未读通知计数
- android - Flutter 插件开发 - 无法在我的项目中使用 ContextCompat
- javascript - 如何调用网格面板外的函数?Extjs
- go - gotext:提取失败:管道:golang.org/x/text/message 未导入