我在使用while循环时遇到逻辑和推理问题,并返回正数n的和,以及n的平方输入之和。请尽可能查看我的代码并提供帮助,谢谢。
演习是: / *写一个简短的Java方法,它取一个整数n并返回它的总和 小于或等于n的所有正整数的平方。 * * /
public class ch1dot7
{
public static void main (String[]args)
{
Scanner input = new Scanner(System.in);
int n, m = 0, sum = 0;
System.out.print("Please enter a value for n: ");
n = input.nextInt();
System.out.println("n is currently: "+n);
if (n <= 0)
{
System.out.print("Please enter a value that is higher than 0 (integer)");
n = input.nextInt();
}
while (sum > n)
{
System.out.print("Please enter a value for m (enter a value greater than n to exit): ");
m = input.nextInt();
if (m < n)
{
sum += m*m;
System.out.println("sum of the squares is: " +sum);
}
sum += m*m;
}
}//end main
}//end class
答案 0 :(得分:0)
你误解了这项任务。作业不会要求您从用户那里获取输入。该方法的唯一输入是n
。
问题是制作一个取整数n的方法,并返回小于n的所有正整数的平方和。
例如,如果n为5,则需要将小于5的数字的平方相加,即数字1到4,如下所示:
(1*1) + (2*2) + (3*3) + (4*4)
1 + 4 + 9 + 16 = 30
你的方法应该返回30
在while
循环中,您将提示用户输入其他内容并将其保存在变量m
中。这不是必需的。
m
。
当计数器变量小于n时,while
循环应该继续,并且计数器应该在每个循环中递增。在1处启动计数器并在该计数器小于n时继续循环。
public static int sumOfSquares(int n) {
// here you can check if n is greater than 0
int counter = 1;
int sum = 0;
while (counter < n) {
// [ sum up the square of the counter ]
counter++;
}
return n;
}