有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java无法在输入正确答案后让代码终止

编写一个名为PasswordChecker的程序,执行以下操作: 1.提示用户输入密码 2.提示用户租用密码 3.检查以确保两个密码条目相同 4.(对于前三次尝试)重复步骤1至3,直到两次正确输入密码。 5.第三次尝试后,如果用户没有正确输入密码,程序需要显示一条信息性消息,指示用户帐户已挂起

我的代码:

import java.util.Scanner;
public class passwordChecker{


public static void main(String [] args){
String  pw1;
String pw2;
int count=0;
Scanner keyboard = new Scanner(System.in);
  do{
   System.out.println("Enter the  password:");
pw1 = keyboard.nextLine();
System.out.println("Renter the password:");
pw2 = keyboard.nextLine();
count++;
if(pw1.equals(pw2))
System.out.println("Correct");

else if(count>=3)
  System.out.println("Account is suspended");

while(pw1==pw2||count>3);
 }
}

共 (2) 个答案

  1. # 1 楼答案

    简单地做

    public class PasswordChecker {
    
        public static void main(String[] args) {
            String pw1;
            String pw2;
            int count = 0;
            Scanner keyboard = new Scanner(System.in);
            System.out.println("Enter the  password:");
            pw1 = keyboard.nextLine();
            while(true){
                System.out.println("Renter the password:");
                pw2 = keyboard.nextLine();
                if (pw1.equals(pw2)) {
                    System.out.println("Correct");
                    break;
                } else if(count == 3){
                    System.out.println("Account is suspended");
                    break;
                }
                count++;
            }
        }
    }
    
  2. # 2 楼答案

    您似乎缺少一个右大括号(您打开了do,但没有在while之前关闭)。您的第一个条件应该是count < 3,我认为您希望在两个String不相等时循环。大概

    do {
        System.out.println("Enter the  password:");
        pw1 = keyboard.nextLine();
        System.out.println("Renter the password:");
        pw2 = keyboard.nextLine();
        count++;
        if (pw1.equals(pw2)) {
            System.out.println("Correct");
        } else if (count >= 3) {
            System.out.println("Account is suspended");
        }
    } while (count < 3 && !pw1.equals(pw2));
    

    编辑

    Object类型不使用==(或!=)的原因是它只测试引用相等性。您需要测试值是否相等(这些String来自不同的行,因此它们不会通过引用比较相等)