猿问

Java 如何以最少的行数打印语句 1000 次

我最近开始用 java 编码,所以我对编码的了解非常有限。我想知道如何以最少的行数打印诸如“Bob ate a burger”之类的行 1000 次。重要提示:我不能使用循环(例如“for”或“while”),但我必须使用方法。1000:1,2,4,5,8,10,20,25,40,50,100,125,200,250,500,1000 的因子我得到的最少是大约 37 行:(我知道这显然不是最接近的)谢谢你这么多。


public class Random{

    public static void main(String [] args){

        twofifty();

        twofifty();

        twofifty();

        twofifty();    

    }

    public static void fives(){

        System.out.println("Bob ate burgers");

        System.out.println("Bob ate burgers");

        System.out.println("Bob ate burgers");

        System.out.println("Bob ate burgers");

        System.out.println("Bob ate burgers");

    }

    public static void fifty()

        fives();

        fives();

        fives();

        fives();

        fives();

        fives();

        fives();

        fives();

        fives();

        fives();

    }

    public static void twofifty(){

        fifty();

        fifty();

        fifty();

        fifty();

        fifty();

    }

}


MM们
浏览 210回答 3
3回答

一只名叫tom的猫

使用递归,即递归调用您的方法并维护一个计数器,当达到 1000 时,终止递归。public class Recusrion{  public static void main(String[] args){   print(0);  }  static void print(int num){    if (num > 1000)      return;    System.out.println(num);    print(++num); }}

有只小跳蛙

您可以使用Stream:public static void print(int times) {&nbsp; &nbsp; IntStream.range(0, times).forEach(i -> System.out.println("Bob ate burgers"));}print(1000);&nbsp; &nbsp; // this is client code您可以使用递归,但问题是times您可以获得的大SacOverflowException:public static void print(int times) {&nbsp; &nbsp; if (times >= 0) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Bob ate burgers");&nbsp; &nbsp; &nbsp; &nbsp; print2(--times);&nbsp; &nbsp; }}print(1000);&nbsp; &nbsp; // this is client code下一个变体使用两种不同的方法来模拟调用堆栈而无需递归:public static void print(int times) {&nbsp; &nbsp; step1(times, 0);}private static void step1(int times, int i) {&nbsp; &nbsp; step2(times, i);}private static void step2(int times, int i) {&nbsp; &nbsp; if (i < times) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Bob ate burgers");&nbsp; &nbsp; &nbsp; &nbsp; step1(times, ++i);&nbsp; &nbsp; }}print(1000);&nbsp; &nbsp; // this is client code

慕的地6264312

其他人可以打高尔夫球这个答案。它旨在“使用方法”。不确定是否foreach算作循环。排序取决于一个人的定义。假设方法存在于一个类中RecursePrint,因此请根据需要进行调整。public void out(int cntr) {&nbsp; &nbsp; System.out.println("Bob's your uncle (" + cntr + ")");}此方法使用 IntStream 和一个foreach. 同样,不确定是否foreach违反循环思想。public void oneLiner(){&nbsp; &nbsp; IntStream.rangeClosed(1, 1000).forEach(i -> out(i));}递归方法(原始)。在这种情况下,该方法会调用自身,直到达到所需的计数。可以将其更改为采用最大值的参数。它使用一个if语句,但没有循环。public void doit(int cntr){&nbsp; &nbsp; if (cntr >= 1000) {&nbsp; &nbsp; &nbsp; &nbsp; return;&nbsp; &nbsp; }&nbsp; &nbsp; out(cntr);&nbsp; &nbsp; doit(++cntr);}public static void main(String[] args){&nbsp; &nbsp; RecursePrint rp = new RecursePrint();&nbsp; &nbsp; rp.doit(0);&nbsp; &nbsp; rp.oneLiner();}
随时随地看视频慕课网APP

相关分类

Java
我要回答