簡體   English   中英

使用遞歸方法在java中打印文本

[英]Making a recursive method to print a text in 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)

你需要做這樣的事情。

首先定義一個函數maxElement ,它將變量數組作為參數。

public static maxElement(String[] variables) {
    return maxElementBis(variables,0);
}

然后調用第二個函數: maxElementBis ,它接受一個額外的參數,表示我們正在處理的變量索引

public static String maxElementBis(String[] variables, int index) {
    if (variables.length < 2) 
        return "not enought variables";
    if (variables.length - index == 2)
        return "Math.max("+ variables[index]+","+variables[index + 1]+")";
    return "Math.max("+ variables[index]+","+maxElementBis(variables,index + 1)+")";

}

如果數組包含少於兩個變量,您將無法執行所需的操作。

如果你只剩下兩個變量,這是你的停止條件,你可以直接返回Math.max(v1,v2)

否則,您將遞歸調用函數maxElementBis

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM