我正在学习如何编码,我面临一些问题,我希望有人可以帮助我。目前,我正在创建一个提示军事状态并显示适当折扣的程序,但如果答案不是给定选项之一,我希望它循环。
这是我的代码:
public static void main(String[] args)
{
char milID = ' ';
char status = ' ';
String validMilitaryID = JOptionPane.showInputDialog("Do you have a valid military ID?");
milID = validMilitaryID.charAt(0);
Scanner valid = new Scanner(System.in);
if (milID == 'Y') {
System.out.printf("%n Are you Active Duty, Retired, or a Dependant?");
status = valid.nextLine().charAt(0);
} else if (milID == 'y'){
System.out.printf("%n Are you Active Duty, Retired, or a Dependant?");
status = valid.nextLine().charAt(0);
}else{
JOptionPane.showMessageDialog(null, "Sorry, you are currently ineligible for a Military Discount");
System.exit(0);
}
if (status == 'A'){
JOptionPane.showMessageDialog(null, "Congratulations! You are eligible to recieve a 15% discount!");
} else if (status == 'R'){
JOptionPane.showMessageDialog(null, "Congratulations! You are eligible to recieve a 13% discount!");
}else if ( status == 'D'){
JOptionPane.showMessageDialog(null, "Congratulations! You are eligible to recieve a 10% discount!");
} else {
JOptionPane.showMessageDialog(null, "Sorry! That was not a valid answer.");
}
System.exit(0);
}//END MAIN
如果有人能够提供帮助,您能解释一下这个过程吗?由于我是Java新手,我想学习而不仅仅是修复。 谢谢!!
答案 0 :(得分:0)
1)您可以将输入以及if代码调用到while循环中
2)如果
,可以使用开关而不是if..else来自逻辑的东西,例如:
boolean checkInput = true;
while (checkInput) {
// now get your input... not coded
switch (milId) {
case "y","Y": bla bla, break;
case "x","X": bla bla, break;
otherwise: bla bla, break;
}}
3)为您的帐户值使用变量;你可以用查找来编码这个
答案 1 :(得分:0)
您的代码中缺少Java(或一般编程)的组成部分,那就是" while循环"。我不知道你到目前为止对Java有多少了解,但是一个while循环会重复其代码块中的内容,直到满足要求为止。如果您在添加错误输入的情况下添加重复调查的功能,则在条件开头的while循环就是您所需要的。
<强>伪代码强>
create variable called correctAnswer
Do you have a military id? Enter y or Y if yes, any other key for no
if yes, correctAnswer = 1
if no, correctAnswer = 0 and while loop is skipped
while correctAnswer = 1
{
Are you active, retired, etc?
If yes, what is your status?
if A, R, or D is given, display congrats message. correctAnswer = 0 //end
if anything other than A, R or D is given, then correctAnswer = 1 //repeat
}
第二个条件块中的while循环不断重复循环,直到给出正确的答案。