0

任务是:

使用方法计算平方并返回答案

使用方法计算立方并返回答案

设置一个while循环来调用这两个方法并输出结果。

我想出了这个,但我也不知道如何在方法中更改变量。

public class Test {
public static void main(String args[])
{

    int number = 1;
    int square;
    int cube;

    square = squareNumber(number);
    cube = cubesNumber(number, square);

    System.out.println("\nNumber\tSquare\tCubes");

while(number <= 5)
    {
        System.out.printf("  %d\t  %d\t %d\n", number, square, cube);
        number++;
    }//end Loop

}//end main

private static int squareNumber(int number)
{
    int square;
    square = number * number;
    return square;

}//end squares method

private static int cubesNumber(int number, int square)
{
    int cube;
    cube = square * number;
    return cube;

}//end squares method
} //end class
4

2 回答 2

0

调用循环中的方法。就像是

while(number <= 5)
{
    square = squareNumber(number);
    cube = cubesNumber(number, square);
    System.out.printf("  %d\t  %d\t %d\n", number, square, cube);
    number++;
} //end Loop

否则,随着循环变量的增加,您的计算 square值和cube值将不会被重新计算。number

于 2016-02-20T20:29:48.913 回答
0

最简单的方法:

public class CubeSquare {
    public static void main(String args[]) {

        int number = 1;
        int square;
        int cube;
        int squareNumber;
        int cubeNumber;

        System.out.println("\nNumber\tSquare\tCubes");

        while (number <= 10) {

            square = number * number;
            cube = square * number;
            System.out.printf(" %d\t \t%d\t \t%d\n", number, square, cube);
            number++;
        } //end Loop

    }//end main

}
于 2017-03-17T13:22:35.043 回答