我是Java的新手,也是while,for和if / else语句的新手。我真的一直在与这个问题的野兽挣扎。
代码和说明如下。它编译,但我没有按预期计算。我不确定这是一个数学逻辑错误,循环布局错误,还是两者兼而有之。
我现在已经磨了很长时间,而且我无法看到它。我觉得我真的很亲密......但还是那么遥远。
代码:
/*
This program uses a while loop to to request two numbers and output (inclusively) the odd numbers between them,
the sum of the even numbers between them, the numbers and their squares between 1 & 10, the sum of the squares
of odd numbers.
*/
import java.io.*;
import java.util.*;
public class SumOfaSquare
{
static Scanner console = new Scanner(System.in);
public static void main (String[] args)
{
int firstnum = 0, secondnum = 0, tempnum = 0;
int sum = 0,squaresum = 0, squarenum = 0;
int number = 1;
String oddOutputMessage = "The odd numbers between" + firstnum + " and " + secondnum + " inclusively are:";
String evenSumMessage = "The sum of all even numbers between " + firstnum + " and " + secondnum + "is: ";
String oddSquareMessage = "The odd numbers and their squares are : ";
String squareMessage = "The numbers and their squares from 1-10 are : ";
System.out.println ("Please enter 2 integers. The first number should be greater than the second: ");
firstnum = console.nextInt();
secondnum = console.nextInt();
//used to find out if first number is greater than the second. If not, inform user of error.
if (firstnum > secondnum)
{
tempnum = firstnum;
System.out.println ("You entered: " + firstnum + " and: " + secondnum);
}
else
System.out.println ("Your first number was not greater than your second number. Please try again.");
//while the frist number is greater, do this....
while (tempnum <= secondnum)
{
//if it's odd....
if (tempnum %2 == 1)
{
oddOutputMessage = (oddOutputMessage + tempnum + " ");
squaresum = (squaresum + tempnum * tempnum);
}
//otherwise it's even..
else
{
sum = sum + tempnum;
evenSumMessage = (evenSumMessage + sum + " ");
tempnum++;
}
}
// figures squares from 1 - 10
while (number <=10)
{
squarenum = (squarenum + number * number);
squareMessage = (squareMessage + number + " " + squarenum);
number++;
}
oddSquareMessage = oddSquareMessage + squaresum;
System.out.println (oddOutputMessage);
System.out.println (oddOutputMessage);
System.out.println (squareMessage);
System.out.println (evenSumMessage);
System.out.println (oddSquareMessage);
}
}
答案 0 :(得分:2)
在第一轮中,请仔细考虑增加tempnum
的条件。什么时候发生奇怪的事情? tempnum
会增加吗?
答案 1 :(得分:0)
您的代码存在许多问题。我宁愿你自己解决这个问题。如果您不知道如何调试代码,可以使用“println”调试来打印出变量。
输入输入3和1并逐行浏览您的程序,并考虑答案将在您的头脑中(或在纸上)。看看它是否符合您的预期结果。
以下是有关您的代码的一般性评论:
dumpOddNumbers(low, high), sumEvenNumbers(low, high), ...
for
个循环。该代码的一个问题是如果第一个数字是&lt;然后是第二个(例如输入1 10),程序永远循环,因为如果数字是奇数,则tempnum不会递增。while (tempnum <= secondnum)
应该是for (int tempnum = firstnum; tempnum <= secondnum; tempnum++)
while (number <= 10)
应为for (int number = 1; number <= 10; number++)
println(msgString + resultValue)
。StringBuilder()
而不是msg = msg + ...
类型的逻辑。效率更高。return
那里。以下代码与评论不符。哪个是对的?
// while the frist number is greater, do this
while (tempnum <= secondnum) {
希望这有帮助。