采用递归方法在Java中打印文本

问题描述 投票:0回答:1

我必须制作一个像这样的程序。首先从输入中获取一个数字,然后获取(数字)*字符串。

例如:

2
a b

3
x1 x2 x3

然后在输出中打印出类似这样的内容:

Math.max(a, b)

Math.max(x1, Math.max(x2, x3))

我想用此代码制作Math.max方法的语法。我回家,你明白了!

最终样本:

输入=

4
a b c d

输出=

Math.max(a, Math.max(b, Math.max(c, d)))

有人可以帮我吗?

java
1个回答
-1
投票

您可以使用以下代码实现以上目标,在这里m递归调用maxElement()函数以实现类似Math.max(a,Math.max(b,Math.max(c,d)))的东西]

public static void main(String args[]){
    int length = 4; //here read the input from scanner
    int[] array = {4, 8, 6 , 10}; //here read this input from scanner
    int max = maxElement(array,0,length);
    System.out.println(max);
}

public static int maxElement(int[] start, int index, int length) {
    if (index<length) {
        return Math.max(start[index], maxElement(start, index+1, length));
    } else {
        return start[length-1];
    }
}

请点击并接受我的回答,如果它适合您。

© www.soinside.com 2019 - 2024. All rights reserved.