我正在使用带有哨兵的 while 循环编写以下程序。
我遇到的问题包括:
(1) 探索如何获取输入的“最小分数”而不等于哨兵值。
(2)仅输入一个整数时,获取“最大分”和“最小分”。
任何帮助将不胜感激。以下是该计划的详细信息:
//Write a program that inputs a series of exam scores as integers.
//The number of scores is not limited.
//Print the number of scores entered and the largest and smallest score entered.
//Use a sentinel to terminate the input.
//Input: Series of exam scores as integers.
//Output: Number of scores entered and the largest and smallest score entered.
import java.util.Scanner;
public class hwk_6_1 {
public static void main(String [] args) {
int exam_score;
int number_of_scores = 0;
int i;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter exam score or -1 to end: ");
exam_score = keyboard.nextInt();
int largest_score = 0;
int smallest_score = 0;
while(exam_score != -1) {
for(i = 0; i < i + exam_score; i++) {
System.out.print("Enter exam score or -1 to end: ");
exam_score = keyboard.nextInt();
number_of_scores = i;
if(exam_score > largest_score) {
largest_score = exam_score;
}
if(exam_score < smallest_score) {
smallest_score = exam_score;
}
}
}
System.out.println("The number of scores entered: " + (number_of_scores + 1) + ".");
System.out.println("Largest score: " + largest_score + ".");
System.out.println("Smallest score: " + smallest_score + ".");
}
}
注意:我们不应该使用“if”来检查哨兵,而只能使用 while 循环;不要使用退出或中断。另外,我们要确保使用哨兵值和两个读取语句。该程序的代码应类似于以下算法:
read data // first data
while not last data {
process data
read data
}
最佳答案
您没有遵循伪代码,这就是您想要的:
read data // first data
while not last data{
process data
read data
}
这就是你所拥有的:
read data // first data
while not last data{
read data // <-- you are reading again and ignoring the first value
process data
}
您需要处理数据并在循环末尾读取下一个数据以遵循目标伪代码。
此外,这种情况可以改善:
for(i = 0; i < i + exam_score; i++)
条件中不需要使用i
,只需检查考试成绩是否为-1
,因此可能是:
for(i = 0; exam_score != -1; i++)
分数计数也存在问题,您将 numer_of_scores
设置为 i
。第一次迭代后,您将值设置为 0,并且读取了两个分数。最好在每次阅读后使用 number_of_scores++
并且根本不要使用 i
。
public static void main(String [] args)
{
int exam_score;
int number_of_scores = 0;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter exam score or -1 to end: ");
exam_score = keyboard.nextInt();
int largest_score = 0;
int smallest_score = 0;
while(exam_score != -1)
{
number_of_scores++;
if(exam_score > largest_score)
{
largest_score = exam_score;
}
if(exam_score < smallest_score)
{
smallest_score = exam_score;
}
System.out.print("Enter exam score or -1 to end: ");
exam_score = keyboard.nextInt();
}
System.out.println("The number of scores entered: " + number_of_scores + ".");
System.out.println("Largest score: " + largest_score + ".");
System.out.println("Smallest score: " + smallest_score + ".");
}
关于java - 使用 Sentinels for Java 进行 While 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39846327/