我不得不使用while、do-while和for循环为一个在线的pre java类编写以下程序。寻找一个小小的解释。提前感谢!
PS在寻找参考书时,这是Java还是Javascript?对于一本好的参考书有什么建议吗?我理解了这个概念,大部分情况下,魔鬼当然是在细节中。
public class ExamsFor {
public static void main(String[] arguments) {
int inputNumber; // One of the exams input by the user.
int sum; // The sum of the exams.
int count; // Number of exams.
Double Avg; // The average of the exams.
/* Initialize the summation and counting variables. */
sum = 0;
count = 0;
/* Read and process the user's input. */
TextIO.put("Please enter the first exam: "); // get the first exam.
inputNumber = TextIO.getlnInt();
for (inputNumber!=0; sum += inputNubmer; count++ ) { // had the while loop below enter here, worked
TextIO.put("Please enter the next exam, or 0 to end: "); // get the next exam.
inputNumber = TextIO.getlnInt();
}
/* Display the result. */
if (count == 0) {
TextIO.putln("You didn't enter any data!");
}
else {
Avg = ((double)sum) / count;
TextIO.putln();
TextIO.putln("You entered " + count + " exams.");
TextIO.putf("The average for the exams entered is %1.2f.\n", Avg);
}
} // end main ()
} // end class ExamsFor
/* Had the following 'while loop' in place of the 'for loop'
while (inputNumber != 0) {
sum += inputNumber; // Add inputNumber to running sum.
count ++; // Count the input by adding 1 to the count.
*/发布于 2010-07-11 08:07:23
您的for循环不应该是:(请注意前面的内容;以及sum+=inputNumber中的拼写错误)
for (;inputNumber!=0; sum += inputNumber, count++ )while循环应该是
while(inputNumber!=0) {
// rest of the things
sum+=inputNumber;
count++;
}发布于 2010-07-11 07:10:08
您可以比较for和while语句,观察到您在迭代构造中主要需要4件事:
condition (A)
B)
C)
BODY)
对于for,您有
for (A; B; C)
BODY而对于while (这里充满了文字笑话:),您的代码如下
A;
while (B)
{
BODY;
C;
}这很简单,不是吗?
发布于 2010-07-11 07:02:10
阅读this并将您的for循环与预期的语法进行比较,看看哪里出了问题。
https://stackoverflow.com/questions/3221132
复制相似问题