如果用户输入了错误的字符,例如" E"或" A"在我的程序中如何向用户输出消息?我在我的程序中谈到的那条线是当用户必须选择输入三个字符P,M或D中的一个时。但是,如果用户输入了另一个没有列出的字符,我想要显示信息的程序。
正如您所看到的,用户输入" E"程序跳到下一步。但是,我希望用户得到通知并再次要求输入正确的值,即" P,M或D" 。
为了做我想要实现的目标,我相信我需要做一个if语句,所以我在这里尝试过。
if((i = P,M,D) && (i < ?)) {
System.out.println("ERROR, please input only P,M or D.");
}
JAVA CODE
String grade;
int yr2cred[] = new int[18];
char yr2grade[] = new char[18];
for (int i = 1; i <= 18; i++) {
System.out.println("Please enter your grade for unit " + i +" "+(username) + ".");
grade = userinput.next();
yr2grade[i - 1] = grade.charAt(0);
if (yr2grade[i - 1] == 'P' || yr2grade[i - 1] == 'p') {
yr2cred[i - 1] = yr2cred[i - 1] + P;
}
if (yr2grade[i - 1] == 'M' || yr2grade[i - 1] == 'm') {
yr2cred[i - 1] = yr2cred[i - 1] + M;
}
if (yr2grade[i - 1] == 'D' || yr2grade[i - 1] == 'd') {
yr2cred[i - 1] = yr2cred[i - 1] + D;
}
}
答案 0 :(得分:0)
可能的代码在这里。我们迭代单位,对于我们要求输入等级值的每个单位,直到输入有效单位。最后打印成绩列表。
import java.util.Arrays;
import java.util.Scanner;
public class CheckInput {
public static void main(String[] args) {
int unitsCount = 18;
String[] unitGrades = new String[unitsCount];
String grade;
Scanner userInput = new Scanner(System.in);
for (int i = 0; i < unitsCount; i++) {
grade = "";
while ( ! (grade.equalsIgnoreCase("P") || grade.equalsIgnoreCase("M") || grade.equalsIgnoreCase("D") ) ) {
if (!"".equals(grade)){
System.out.println("ERROR, please input only P,M or D.");
}
System.out.print("Please enter your grade for unit " + i + ": ");
grade = userInput.next();
}
unitGrades[i] = grade;
}
System.out.println("Unit grades: "+Arrays.toString(unitGrades));
}
}
答案 1 :(得分:0)
您可以在 for 循环中使用 while 循环执行此操作:
for (int i = 1; i <= 18; i++) {
while (grade.equals("")) {
System.out.println("Please enter your grade for unit " + i + " " + username + ".");
grade = userinput.next().toLowerCase();
yr2grade[i - 1] = grade.charAt(0);
if (yr2grade[i - 1] == 'p') {
yr2cred[i - 1] = yr2cred[i - 1] + P;
} else if (yr2grade[i - 1] == 'm') {
yr2cred[i - 1] = yr2cred[i - 1] + M;
} else if (yr2grade[i - 1] == 'd') {
yr2cred[i - 1] = yr2cred[i - 1] + D;
} else {
System.err.println("Invalid Grade Supplied! Try Again.\n");
grade = "";
}
}
grade = "";
}