更新驱动整数,使其在一行中

问题描述

我的代码逻辑有效,但我遇到的问题是在 System.out.println(); 行中。

我的代码的作用示例:

这将从您按顺序放入输入参数 (n) 中的数字生成整数,并将它们置于输入参数 (n) 中的幂。

这意味着下面的输入参数 n 等于 3。

totalCue(3) = 1^3 + 2^3 + 3^3 显然等于 36

我希望我的输出是这个 1 + 8 + 27 = 36 但它是这个

1 +  = 1
8 +  = 9
27 +  = 36

我该怎么做才能解决此问题或仅更新 1 行中的所有数字。顺便说一句:我也试过只做 System.out.print();,但没有奏效。

我的代码如下:

public class CUetoTAL  {
    public int totalCue(int n)
    {
        int result = 0; 
        
       
        for (int x = 1; x <= n; x++){
            result += (int)Math.pow(x,n);
            System.out.print((int)Math.pow(x,n)+" + " + " = " +result);
        }
        return result;
        
        
    }
    
    public static void main(String args[]){
        
        CUetoTAL n = new CUetoTAL();
        
        n.totalCue(3);
        
        
    }
}

解决方法

  1. 将您的结果附加到列表中
  2. 连接列表中的元素以获取 LHS
  3. 对列表中的元素求和以获得 RHS
        List<Integer> list = new ArrayList<>();

        // compute powers and append to list
        for (int x = 1; x <= n; x++){
            list.add((int) Math.pow(x,3));
        }

        // generate the LHS by concatenating with " + " 
        String prefix = list.stream().map(String::valueOf).collect(Collectors.joining(" + "));

        // print the LHS and RHS sum 
        System.out.println(prefix + " = " + list.stream().reduce(Integer::sum).get());

,

你的逻辑有问题。您不想每次都打印“= 结果”。

    String plus = "";
    for (int x = 1; x <= n; x++){
        int term = (int)Math.pow(x,n);
        result += term;
        System.out.print(plus + term);
        plus = " + ";
    }
    System.out.println(" = " + result);

两个注意事项:

  1. 我添加了一个额外的变量 term - 不要进行两次相同的计算。

  2. 字符串 'plus' 很好用,只是为了在第一个术语之前不打印任何内容,然后在每个后续术语上打印 '+'。

,

使用三元组进行字符串连接。

for (int x = 1; x <= n; x++){
        int pow = (int)Math.pow(x,n);
        result += pow;
        String concat = x == n ? " = " : " + ";
        System.out.print(pow + "" + concat);
    }
    System.out.print(result);

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...