javaloopsfor-loopsystem.out

Update powered integers so its in one line


The logic of my code works but the problem I'm having is in the System.out.println(); line.

Example of what my code does:

This will generate integers from the number you put in the input parameter(n) in order and put them to the power of what you put in the input parameter(n).

This means below the input parameter n is equal to 3.

totalCue(3) = 1^3 + 2^3 + 3^3 which will obviously equal 36

I want my ouput to be this 1 + 8 + 27 = 36 but instead it is this

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

What do I do this fix this or update all the numbers in only 1 line. BTW: I also tried doing just System.out.print(); but it didn't work.

My Code Below:

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

Solution

  • Your logic is flawed. You don't want to print the '= result' every time.

        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);
    

    Two notes:

    1. I added an extra variable term - don't do the same calculation twice.

    2. The string 'plus' caters nice and simply for printing nothing before the first term, and then '+' on each subsequent term.