首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在java中不带任何循环地打印1到10

在java中不带任何循环地打印1到10
EN

Stack Overflow用户
提问于 2012-02-23 06:28:13
回答 2查看 19.6K关注 0票数 5

可能重复:

Display numbers from 1 to 100 without loops or conditions

面试问题:

在java中打印1到10没有任何循环。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-02-23 06:28:39

简单的方法:System.out.println值:

代码语言:javascript
复制
    System.out.println(1);
    System.out.println(2);
    System.out.println(3);
    System.out.println(4);
    System.out.println(5);
    System.out.println(6);
    System.out.println(7);
    System.out.println(8);
    System.out.println(9);
    System.out.println(10);

复杂方式:使用递归

代码语言:javascript
复制
public void recursiveMe(int n) {
    if(n <= 10) {// 10 is the max limit
        System.out.println(n);//print n
        recursiveMe(n+1);//call recursiveMe with n=n+1
    }
}
recursiveMe(1); // call the function with 1.
票数 21
EN

Stack Overflow用户

发布于 2012-02-23 08:57:35

如果您喜欢您的程序钝,没有循环,条件语句或主要方法。

代码语言:javascript
复制
static int i = 0;
static {
    try {
        recurse();
    } catch (Throwable t) {
        System.exit(0);
    }
}

private static void recurse() {
    System.out.print(++i + 0 / (i - 11) + " ");
    recurse();
}

这使用了一个循环,但可能是一个有趣的答案。

代码语言:javascript
复制
Random random = new Random(-6732303926L);
for(int i = 0; i < 10; i++)
    System.out.print((1+random.nextInt(10))+" ");
}

您可以将其重构为不使用循环。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9408210

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档