如何使用不正确的输入循环java
我目前正在学习如何编码,我面临着一个小问题,我希望有人能帮助我。目前,我正在创建一个程序,提示输入军事状态并显示适当的折扣,但如果答案不是给定的选项之一,我希望它能够循环 这是我的代码:如何使用不正确的输入循环java,java,loops,Java,Loops,我目前正在学习如何编码,我面临着一个小问题,我希望有人能帮助我。目前,我正在创建一个程序,提示输入军事状态并显示适当的折扣,但如果答案不是给定的选项之一,我希望它能够循环 这是我的代码: public static void main(String[] args) { char milID = ' '; char status = ' '; String validMilitaryID = JOptionPane.showInputDialog("Do y
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新手,所以我想学习,而不仅仅是解决问题。
谢谢 1)您可以将输入和if代码调用到while循环中
2) 也许用一个开关来代替if.。else if
逻辑中的某些东西,例如:
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) 为你的账户价值使用一个变量;您可以通过查找来编写代码,代码中缺少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循环不断重复循环,直到给出正确的答案 阅读while loop你对loop了解多少?使用do…while(表达)只是好奇。为什么不在您有系统输出的地方使用
JOptionPane
?。。。或者JOptionPane.showInputDialog
而不是扫描仪(您不关闭),我将它们集成到我的代码中,我不确定问题出在哪里,但当状态出现错误时,它不会重新启动循环。而(!验证);{case'd':System.out.printf(“%n恭喜%s折扣!”,折扣.get(3));verify=false;break;default:System.err.println(“这是无效状态”);