我正在制作GPA计算器,这将提示用户输入每个班级的班级名称,学分和预期的字母等级。当提示输入预期的字母等级时,我在提出验证用户输入的有效方法时遇到问题。这就是我到目前为止所拥有的:
events: {
'click a[href!=""]': 'onClick'
}
onClick: function(ev)
{
try {
var now = new Date()
, hoursSinceLastRefresh = Math.abs(now - this.lastRefresh) / 36e5
, href = ev.currentTarget.attr('href')
, isVirtualNavigation = href.substr(0,1) === '#'
, pageExpired = hoursSinceLastRefresh >= 24;
// if is internal navigation
if (isVirtualNavigation && pageExpired){
href.reload(true);
}
}
catch (ex) {
}
}
我尝试在此过程中使用数组,但不确定这是否是最好的方法。我想要的只是当用户没有输入正确的字母等级然后提示他们直到他们这样做时才会收到提醒。
我已经尝试在switch语句中使用System.out.println("What grade did you earn in the class: A, A-, B+, B, B-, C+, C, C-, D+, D, or F?");
String[] grades ={"A", "A-", "B+", "B", "B-", "C+", "C", "C-", "D+", "D", "F"};
firstGrade = scanner.nextLine();
while (!firstGrade.equals(grades)) {
System.out.println("Invalid input, please type a valid letter grade");
firstGrade = scanner.nextLine();
}
switch(firstGrade){
case "A":
System.out.println("Your GPA from " + firstClass +" is a 4.0");
break;
case "A-":
System.out.println("Your GPA from " + firstClass +" is a 3.7");
break;
case "B+":
System.out.println("Your GPA from " + firstClass +" is a 3.3");
break;
case "B":
System.out.println("Your GPA from " + firstClass +" is a 3.0");
break;
case "B-":
System.out.println("Your GPA from " + firstClass +" is a 2.7");
break;
case "C+":
System.out.println("Your GPA from " + firstClass +" is a 2.3");
break;
case "C":
System.out.println("Your GPA from " + firstClass +" is a 2.0");
break;
case "C-":
System.out.println("Your GPA from " + firstClass +" is a 1.7");
break;
case "D+":
System.out.println("Your GPA from " + firstClass +" is a 1.3");
break;
case "D":
System.out.println("Your GPA from " + firstClass +" is a 1.0");
break;
case "F":
System.out.println("Your GPA from " + firstClass +" is a 0.0");
break;
}
但是在第一次失败后无法让程序验证输入。
有什么建议吗?
答案 0 :(得分:2)
我强烈建议您使用Map<String, Double>
并完全删除switch
。如果您使用Map
(因为它保留了广告订单),您可以使用LinkedHashMap
来显示您的选项。最后,循环直到用户输入有效等级,然后显示相应的GPA。像,
Map<String, Double> gradeMap = new LinkedHashMap<>();
gradeMap.put("A", 4.0);
gradeMap.put("A-", 3.7);
gradeMap.put("B+", 3.3);
gradeMap.put("B", 3.0);
gradeMap.put("B-", 2.7);
gradeMap.put("C+", 2.3);
gradeMap.put("C", 2.0);
gradeMap.put("C-", 1.7);
gradeMap.put("D+", 1.3);
gradeMap.put("D-", 1.0);
gradeMap.put("F", 0.0);
System.out.printf("What grade did you earn in the class: %s?%n",
gradeMap.keySet().stream().collect(Collectors.joining(", ")));
String firstGrade = scanner.nextLine();
while (!gradeMap.containsKey(firstGrade)) {
System.out.println("Invalid input, please type a valid letter grade");
firstGrade = scanner.nextLine();
}
System.out.printf("Your GPA from %s is a %.1f%n", firstClass,
gradeMap.get(firstGrade));