How can I use a formula in a for loop in java

I am a beginner java programmer, studying off basic youtube videos and overflow forums, and i came across a question on an textbook sheet that asked me to use a for loop program and print this table out as well as fill in each blank

Number   Square   Cube   (n+1)/(2n-18)
1         #        #          #
2         #        #          #
3         #        #          #
4         #        #          #
5         #        #          #

I thought I should try it out to test myself. I came up with the following program that works perfectly for the Number, Square and Cube part of the table, but I don’t understand how to generate the numbers using the given formula. The formula I initialized as a variable (double) doesn’t print the actual results, and I honestly don’t have a clue as to what to do. I’d rather a simple explanation than a complex one and simple changes to the code rather than complex. As I said I am a beginner, and many different methods may go right over my head. Thank you so much in advance (also an extra task asks that I print out the sums of each column. I don’t know how to do that at all, and would like an explanation if possible, but wouldn’t mind if I don’t receive one)

int number;
int maxValue;

Scanner keyboard = new Scanner(;
System.out.println("how many numbers do you want the max value to be");
maxValue = keyboard.nextInt();

System.out.println("NumbertSquaretCube (n+1)/(2n-18)");
for (number = 1; number <= maxValue; number++) {
    double formula = (number + 1) / (number * 2);
        number + "ttt" + number * number + "ttt" +
        number * number * number + "ttt" + formula);


Your formula does not match the textbook. Try this:

System.out.println("NumbertSquaretCube (n+1)/(2n-18)");

for (int number=1; number <= maxValue; number++) {
    double square = Math.pow(number, 2);
    double cube = Math.pow(number, 3);
    double formula = (number + 1) / (number * 2 - 18);
    System.out.println(number + "ttt" + square + "ttt" + cube + "ttt" + formula);

Note: As pointed out by @MauricePerry an input of 9 would cause a divide by zero. Rather than try to catch this unchecked exception, I think you should control your input values so that this does not happen.

Leave a Reply

Your email address will not be published. Required fields are marked *