java - 使用递归方法在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);
}
}
}
}
解决方案
您可以使用以下代码来实现上述功能,这里 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)
推荐阅读
- javascript - Javascript删除滚动类
- pandas - 从列名重新索引熊猫数据框
- javascript - 尝试使用AngularJS根据表外元素的表字段进行过滤
- javascript - 每列仅添加 4 个项目
- javascript - 如何使用(或不使用)jQuery 加载外部文件句柄表达式?
- redirect - 从一个域的英文版重定向到 wix 的新域
- cordova - 成功构建和部署后,离子应用程序流中不会发生持续部署和实时更新
- html-table - 如何在降价中使用 col span?
- iis - 从 ApplicationHost.config 获取 IIS 工作进程
- javascript - Javascript 从 json 填充选择选项