我设法完成了这个问题的一部分但是我遇到了立方体方法的问题。 我需要在cube方法中调用square方法来返回cube结果。 示例:要将数字5平方,结果将为25.然后,我将此方法调用到cube方法中以返回答案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;
}
}
我很感激这个很棒的反馈。真有帮助。谢谢大家。
答案 0 :(得分: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);
}
}