我正在尝试创建一个检查用户密码的程序。我希望程序在用户正确的情况下结束,但如果不是,我希望它只询问4次。
问题:即使您确实正确获取了密码,程序也会继续询问猜测密码。如果你弄错了,它会错误地提问。我该如何解决这个问题?
import java.util.Scanner;
public class HowToAdd {
public static void main (String [] args){
Scanner input = new Scanner (System.in);
int trys = 0;
String password=null;
do{
System.out.println("Guess the password");
password = input.next();
if(password.equalsIgnoreCase("Password")){
System.out.println("Great job");
}else{
System.out.println("Try again");
input.next();
trys++;
}
}while(trys<2);
System.out.println("Try again later!");
input.close();
}
}
答案 0 :(得分:2)
你只需要添加一个休息:
if(password.equalsIgnoreCase("Password")){
System.out.println("Great job");
break;
}
答案 1 :(得分:1)
我不仅添加了一个中断来修复输入正确密码时不离开循环的问题,而且还添加了一些其他内容来帮助您查看以下内容:
public static void main (String [] args){
Scanner input = new Scanner (System.in);
int trys = 0;
String password=null;
System.out.println("Guess the password:");
while(trys<2)
{
password = input.next();
if(password.equalsIgnoreCase("Password")){
System.out.println("Great job");
break;
}else{
trys++;
if(trys != 2)
{
System.out.println("Try again:");
}
}
}
if(trys == 2)
{
System.out.println("Try again later!");
}
input.close();
}
尝试这一点,如果使用break;
语句正确,它将突破循环。此外,它只会在第一次尝试时显示猜测密码,然后再尝试。如果他们猜对了,也不会再说再试,因为它会检查他们是否猜错了两次。
答案 2 :(得分:0)
您可以使用break
关键字进行修复,例如:
if(password.equalsIgnoreCase("Password")){
System.out.println("Great job");
break;
}
此处解释了break
:
答案 3 :(得分:0)
您可以在不使用break
语句的情况下完成所需的操作。
试着看看我的代码流程。
Scanner scn = new Scanner(System.in);
int tries=0;
String pw = "";
System.out.println("Guess the password");
pw = scn.nextLine();
while(!pw.equalsIgnoreCase("Password") && tries < 3){
tries++;
System.out.println("Try again");
pw = scn.nextLine();
}
if(tries >= 3)
System.out.println("Try again later!");
else
System.out.println("Great job!");
TEST RUN 1:
Guess the password
1st try
Try again
2nd try
Try again
3rd try
Try again
last try
Try again later!
TEST RUN 2:
Guess the password
password
Great job!
答案 4 :(得分:0)
以下是代码的另一种变体:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int trys = 0;
String password = null;
// create variable for a number of tries
int numberOfCheks = 4;
do {
System.out.println("Guess the password");
password = input.nextLine();
if (password.equalsIgnoreCase("Password")) {
System.out.println("Great job");
break;
} else if (++trys == numberOfCheks) {
//Break if you've used all your tries
System.out.println("Try again later!");
break;
} else {
System.out.println("Try again");
// input.next(); - Useless. You don't handle it. Removed
}
//There is already tries number check. So 'true' can be used as the condition.
} while (true);
input.close();
}