首页 > 解决方案 > 使用递归方法在java中打印文本

问题描述

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

例如:

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)))

有人能帮我吗?

我为它编写的代码,您能建议我进行一些更改以使其更好吗?

import java.util.*;

public class Main {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int n = input.nextInt();
    String[] r = new String[n];
    for (int i = 0; i < n; i++) {
      r[i] = input.next();
    }
    printmax(r);

  }
  public static int i = 0 , j = 0;
  public static boolean last = false;
  public static void printmax(String [] r){
    if (last == true) {
      System.out.print(r[r.length - 1]);
      while (j < r.length - 1){ System.out.print(")");
        j++;
      }
    }
    if (r.length == 2) System.out.print("Math.max(" +r[0] + ", " + r[1] + ")");
    if (r.length > 2) {
      while (i < r.length -1) {
        if (i == r.length -2) last = true;
        System.out.print("Math.max(" + r[i] + ", ");
        i++;
        printmax(r);
      }
    }
  }
}

标签: javastringstringbuilder

解决方案


您可以使用以下代码来实现上述功能,这里 m 递归调用 maxElement() 函数来实现类似 Math.max(a, Math.max(b, Math.max(c, d)))

public static void main(String args[]){
    int length = 2; //here read the input from scanner
    String[] array = {"a", "b"}; //here read this input from scanner
    String max = maxElement(array,0,length);
    System.out.println(max);
}
    
public static String maxElement(String[] start, int index, int length) {
    if (index<length-1) {
        return "Math.max(" + start[index]  +  ", " + maxElement(start, index+1, length)+ ")";
    } else {
        return start[length-1];
    }
}

输出:Math.max(a, b)


推荐阅读