用java输出8+88+888

用java输出8+88+888+8888,而不是它们相加的值


public class Main {
    public static void main(String[] args) {
        String s1 = "8";
        String s2 = s1 + "8";
        String s3 = s2 + "8";
        String s4 = s3 + "8";
        String result = s1 + " + " + s2 + " + " + s3 + " + " + s4;
        System.out.println(result);
    }
}

输出结果为:

8 + 88 + 888 + 8888


这里的关键是要使用字符串拼接符号 "+",把每个数都转换成字符串类型后再拼接。

  • 使用循环,参考如下:
    public static void main(String args[]) {
          int n = 4;
          String ori = "8";
          String str = "";
          StringBuilder result = new StringBuilder();
          for (int i = 0; i < n; i++) {
              str += ori;
              if (i == n - 1) {
                  result.append(str);
              } else {
                  result.append(str).append("+");
              }
          }
          System.out.println(result.toString());
    }
    

请说明下具体的背景,是否有什么规则,是否支持动态变化等,比如根据输入的某个参数生成
还是说直接字符串传输出"8+88+888+8888",应该不是吧