Making a recursive method to print a text in java

Sepehr Zamani :

I have to make a program which works like this. first it gets a number from input and then it gets (number) * strings.

for example:

2
a b

or

3
x1 x2 x3

then in the output it prints something like this:

Math.max(a, b)

or

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

I want to make Math.max method syntax with this code. I hope you understood!

Another Sample Input & output:

Input =

4
a b c d

Output =

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

can someone help me?

The code I've wrote for it, can you suggest me some changes to make it better?

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);
      }
    }
  }
}
MOnkey :

You can use the following code to achieve the above, here m calling maxElement() function recursively to achieve somthing like this 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];
    }
}

Please check and accept my answer by clicking tick if it will work for you.

Output: Math.max(a, b)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=12191&siteId=1