问题:通过键盘录入某学生的6科成绩,分值在[0,100]之间,不符合录入规则请重新录入。
JAVA实现
int[] scores = new int[6];
Scanner sc = new Scanner(System.in);
for (int i = 0; i < scores.length; ) {
int score = sc.nextInt();
if (score >= 0 && score <= 100) {
scores[i] = score;
i++;
} else {
System.out.println("again");
}
}
for (int i = 0; i < scores.length; i++) {
System.out.println(scores[i]);
}
Python实现
score = [ 0 for i in range(6)]
i = 0
while True:
x = int(input())
if 0<= x <= 100:
score[i] = x
i += 1
else:
print('again')
if i == len(score):
break
print(score)
print('--------')
print(score)
两端代码都能做到对于不符合要求的录入做无效处理,且不占用6次有效录入机会。