简体   繁体   English

可以使用迭代在Java中生成字符串吗?

[英]Possible to use iteration to produce a string in Java?

So I have an array of doubles, which represent the coefficients of a polynomial. 因此,我有一个双精度数组,表示一个多项式的系数。 I want to have a function that returns a string of the polynomial. 我想有一个返回多项式字符串的函数。

So coeffs = [1.3, 4.5, 6.0] 所以coeffs = [1.3,4.5,6.0]

the function will produces a string 该函数将产生一个字符串

"1.3x^2 + 4.5x + 6.0" “ 1.3x ^ 2 + 4.5x + 6.0”

I've been thinking about iteration to solve this, but I keep getting errors. 我一直在考虑迭代来解决这个问题,但是我一直在出错。 Assume array coeffs has already been constructed. 假设数组系数已经构建。

public String toString()
{
    int len = coeffs.length;
    return 
    for(int i = 0; i < len ; ++i)
    {
        for(int j = len; len > 0; len--)
        {
            return this.coeffs[i] + "x^(" + len + ")" + ;
        }
    }
}
public String toString(){
    int len = coeffs.length;
    StringBuilder return_value =new StringBuilder();

    // Add all the x to the power of something
    for(int i = 0; i < len-1 ; i++)
        return_value += this.coeffs[i]+"x^"+len-i-1+ " + ";

     // last one has no x.
     return_value += this.coeffs[len-1];
}

You can also put another case if you don't want to have 2x^2 + 3x^1 + 5; 如果您不想有2x ^ 2 + 3x ^ 1 + 5,也可以放另一种情况。 (so, the x will be a special case as well) (因此,x也将是特例)

Edit: 编辑:
Like Kewin suggested, this will throw an exception is length is 0. 像Kewin建议的那样,这将引发一个异常,即长度为0。
Note you'll have to handle extreme cases, and think about what happens if one of the coeffs is 0 ( you should just skip that iteration ) :) 请注意,您必须处理极端情况,并考虑如果系数之一为0(会跳过该迭代)会发生什么情况:)

try below code: 试试下面的代码:

public String toString(){
int len = coeffs.length;
StringBuilder sb=new StringBuilder();
return 
    for(int i = 0; i < len ; ++i){
            for(int j = len; len > 0; len--){
                return sb.append(this.coeffs[i] + "x^(" + len + ")");

                    }
        }
    }

As mentioned you cant return a loop. 如前所述,您无法返回循环。 you would have to do something like this 你将不得不做这样的事情

public String toString()
{
    int len = coeffs.length;
    String result = "";
    int j = coeffs.length-1;

    for(int i = 0; i < len ; ++i)
    {
        result += coeffs[i]+"x^("+j+")+" ; 
        j--;
    }

    return result.substring(0,result.length-1);
}

How about this? 这个怎么样?

public String toString(){
    int len = coeffs.length;
    StringBuilder result = new StringBuilder();
    for(int i = 0; i < len; ++i){
            int power = ((i-len+1)*-1)
            result.append("" + coeffs[i] + "x^(" + power + ")");
            if (i < (len - 1)){ result.append(" + "); }
    }
    return result.toString();
}

Gives

1.3x^(2) + 4.5x^(1) + 6.0x^(0)

I'm not sure if that's the format you want however(?) 我不确定这是否是您想要的格式(?)

How about this? 这个怎么样?

public String toString(){
  int len = coeffs.length;
  String equation = '';
  String power = '';
  for(int i = len - 1; i > 0; i--) {
    power = (i > 1 ? 'x^' + i : 'x');
    equation += (coeffs[len - 1 - i] + variable + " ");
  }
  equation += coeffs[0];
}

You can try this: 您可以尝试以下方法:

  double[] coeffs = { 1.3, 4.5, 6.0 };

    StringBuilder sb = new StringBuilder();

    int len = coeffs.length;

    for (int i = 0; i < len - 1; i++) {
        sb.append(coeffs[i]).append('x');
        if (len - 1 - i == 1) {
            sb.append('+').append(' ');
        } else {
            sb.append('^').append(len - i - 1).append('+').append(' ');
        }
    }
    sb.append(coeffs[len - 1]);// Append last element

    System.out.println(sb.toString());// Print "1.3x^2 + 4.5x + 6.0"

Output result in Console: 在控制台中输出结果:

1.3x^2+ 4.5x+ 6.0

You can try this as well. 您也可以尝试一下。

float[] coeffs = new float[]{1.4f, 1.3f, 4.5f, 6.0f};
if (coeffs == null || coeffs.length == 0) {
    return;
}
int power = coeffs.length - 1;
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < coeffs.length; i++) {
    if(power == 0) {
        stringBuilder.append(" + " + coeffs[i]);
    } else if(power == 1) {
        stringBuilder.append(" + " + coeffs[i] + "x");
    } else {
        stringBuilder.append(" + " + coeffs[i] + "x^" + power);
    }
    power--;
}
System.out.println(stringBuilder.substring(3));
double [] coeff = {1.34,2.4,5.6};
String finalStr = "";

if(coeff.length>0){
    for(int i=coeff.length-1,j=0;i>=0 && j<coeff.length;i--,j++){
        finalStr = finalStr+coeff[j]+" "+"x^"+i+" + ";
        finalStr = (i==0)?finalStr.replace("x^0 + ", ""):finalStr;
    }
}

Generate finalStr as 1.34 x^2 + 2.4 x^1 + 5.6 生成finalStr1.34 x^2 + 2.4 x^1 + 5.6

What about this 那这个呢

 public static String polyToString() {
  double[] coeffs = new double[] { 0.1, 0.2, 0.3, 1.1, 2.2, 1.3, 4.5, 6.0 };
  int len = coeffs.length;
  StringBuilder sb = new StringBuilder();

  if(len==0)
    return "";
  if(len==1)
    return ""+coeffs[0];

  for (int i = 3; i <= len; i++) {
    sb.append(coeffs[len - i] + "x^" + (len - i + 2) + " + ");
  }

  if (len >= 2) {
    sb.append(coeffs[len - 2] + "x + " + coeffs[len - 1]);
  }
  return sb.toString();

} }

Out 退房

1.3x^7 + 2.2x^6 + 1.1x^5 + 0.3x^4 + 0.2x^3 + 0.1x^2 + 4.5x + 6.0

Something along the lines of the following might be what you are looking for. 您可能正在寻找以下类似的东西。 Strictly speaking the code below does not use iteration. 严格来说,以下代码不使用迭代。 It is possible to iterate over the values array. 可以遍历values数组。 However, having an integer for the current index value makes it easier to determine if 'x' is needed and the correct format for the exponent (if any). 但是,为当前索引值使用整数可以更轻松地确定是否需要“ x”以及指数的正确格式(如果有)。

public final class Test1 {
  /*
   * The main routine is where execution actually starts
   */
  public static void main(String[] args) {
    System.out.println((new Coeffs()).toString());
  }
}  

class Coeffs {
  double[] values = new double[]  {1.3, 4.5, 6.0};
  public String toString() {
    int                 valuesLen = values.length;
    int                 exponent;
    StringBuffer        result = new StringBuffer();
    for (int i = 0; i < valuesLen; i++) {
      if (result.length() > 0) 
        result.append(" + ");
      result.append(((Double) values[i]).toString());
      exponent = valuesLen - i - 1;
      if (exponent > 0)
        result.append("x");
      if (exponent > 1) {
        result.append("^");
        result.append(((Integer) exponent).toString());
      }        
    }
    return new String(result);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM