不得不使用while,do-while和for循环为在线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.
*/
Run Code Online (Sandbox Code Playgroud)
你可以比较两者for和while语句观察,你在迭代结构中主要需要4个东西:
A)B)C)BODY)因为for你有
for (A; B; C)
BODY
Run Code Online (Sandbox Code Playgroud)
而对于while(在这里充满了单词笑话:)你有类似的东西
A;
while (B)
{
BODY;
C;
}
Run Code Online (Sandbox Code Playgroud)
这很简单,不是吗?