2014-11-24 76 views
0

写一个程序叫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); 
} 
} 
+0

您可能要粘贴整个主要方法到右大括号(}),它将使这更容易向你解释。 – 2014-11-24 03:56:19

回答

4

你似乎缺少一个右括号(打开dowhile之前不要关闭)。你的第一个条件应该是count < 3,我认为你想循环,而两个String(s)不相等。喜欢的东西,

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(s)来自不同的行,因此它们不会通过参考进行比较)。

0

这样做只是

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++; 
     } 
    } 
}