0

我已经设法完成了这个问题的一部分,但我遇到了立方体方法的问题。我需要从多维数据集方法中调用 square 方法来返回多维数据集结果。示例:对数字 5 求平方,结果将是 25。然后我将此方法调用到立方体方法中以返回答案 125。有人可以告诉我哪里出错了吗?

这是我的代码:

import java.util.*;
public class ExamPaper2011
{
public static void main(String [] args){

    int totalSquared = 0;
    int totalCubed = 0;

    cubedNumber(totalSquared, totalCubed);
}

 public static int squaredNumber(int totalSquared){

    Scanner in = new Scanner(System.in);

    System.out.print("Please enter a number to square: ");
    int numSquare = in.nextInt();
    System.out.println("You entered " + numSquare);
    totalSquared = (int) Math.pow (numSquare, 2); 
    System.out.println("The number squared is " + totalSquared);
    return totalSquared;
}

public static int cubedNumber(int totalSquared, int totalCubed){
    squaredNumber(totalSquared);
    totalSquared = (int) Math.sqrt(totalSquared * totalSquared);
    System.out.println(totalSquared);
    totalCubed = totalSquared;
    totalCubed = (int) Math.pow (numSquare, 3); 
    return totalCubed;
}

}

方法 cubedNumber 似乎返回 0。非常感谢任何帮助。请原谅我的基本代码。这是一个班级会议。

这是答案。再次感谢大家。

import java.util.*;
public class ExamPaper2011
{
public static void main(String [] args){

    Scanner in = new Scanner(System.in);

    System.out.print("Please enter a number to square and cube: ");
    int n = in.nextInt();

    cubedNumber(n);

}

public static int squaredNumber(int n){//Question 4
    System.out.println("You entered " + n);
    n = n * n;
    System.out.println("Squared = " + n);
    return n;
}

public static int cubedNumber(int n){
    squaredNumber(n); 
    n = n * squaredNumber(n);
    System.out.println("Cubed = " + n);
    return n;
}

}

我很感激这个很棒的反馈。真的很有帮助。谢谢你们。

4

1 回答 1

1

如何将用户输入检查部分移出您的逻辑方法?

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

        Scanner in = new Scanner(System.in);

        System.out.print("Please enter a number: ");
        //here you get user input, maybe ask user what calculation he wants to do ^2 Or ^3
        //...get n from user input.
        //if he wants square
        print squaredNumber(n);
        //if he wants cubed
        print cubedNumber(n);
    }

    public static int squaredNumber(int n){
        return n*n;

    }

    public static int cubedNumber(int n){
        return n*squaredNumber(n);
    }

}
于 2013-02-18T18:14:40.990 回答