i want a program which asks the user to type the password. If he goes wrong three times exit.this is my code

import java.io.*;
class password1
{
public static void main(String args[])throws Exception
{
String pass="samarth";
boolean flag=false;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String [] password=new String[20];
int i;
for(i=0;i<3;i++)
{
System.out.println("enter password");
 password[i]=br.readLine();//*
if(pass.compareTo(password[i])==0)
{
flag=true;
break;
}
else
{
System.out.println("try again");
 password[i]=br.readLine();
}
}
if(flag)
System.out.println("welcome");
}
}


the line marked with * is the problem because it asks for password again

enter password
nikhil
try again
nikhi//i have to put this because of the line marked *
enter password
nikh
try again
nikh
enter password
samarth
welcome

i am sorry in advance if i am not clear

String [] password=new String[20];

what's the use of the array of string? you are saving all the passwords inputed, why?

try this

import java.io.*;
class password1{
            public static void main(String args[])throws Exception
           {
                        String pass="samarth";
                        boolean flag=false;
                        BufferedReader br=new BufferedReader                    (new InputStreamReader(System.in));
                       String password=new String;
                        
                       int i;
                       for(i=0;i<3;i++)
                      {
                                   System.out.println("enter password");
                                   password = br.readLine();
                                  if(pass.compareTo(password)==0){
                                              flag=true;
                                              break;
                                  }
                                  else{
                                             System.out.println("try again");
                                  }
                    }
                    if(flag)
                             System.out.println("welcome");
            }
}

i just did it on the spot, i didnt compile it, just try it for now. i just did a little editing on ur code. i dont have java here on my laptop so i can't compile that code.

the proble u encountered is because of ur second readLine statement in the else statement:

if(pass.compareTo(password)==0)
{
flag=true;
break;
}
else
{
System.out.println("try again");
password=br.readLine();
}

thanks it worked

it was silly on my part i guess

Please don't write whole posts in code tags, instead use code tags only whenever you need to post a snippet of code.

>it was silly on my part i guess
No, it's certainly not silly to ask for help, this is probably the best thing you could do, at least you understand your mistake now, and you probably won't make it again :)

This question has already been answered. Start a new discussion instead.