Click here to Skip to main content
15,893,904 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
static void Main(string[] args)
{
string username = "coffee";
            string password = "tea";

            Console.WriteLine("Enter your name : ");
            username = Console.ReadLine();

            Console.WriteLine("Enter your password : ");
            password = Console.ReadLine();

            for (int i = 0; i <= 2; i++)
            {
                if (username == "coffee" && password == "tea")
                {
                    Console.WriteLine("\n");
                    Console.WriteLine("Welcome mr coffee");
                    Console.ReadLine();
                    break;
                }

                else
                {
                    Console.WriteLine("\n");
                    Console.WriteLine("try again");

                    Console.WriteLine("Enter your name : ");
                    username = Console.ReadLine();

                    Console.WriteLine("Enter your password : ");
                    password = Console.ReadLine();
                    Console.WriteLine("\n");
                }
            }
            Console.WriteLine("Invalid data try again later");
            Console.ReadLine();
}


What I have tried:

what's wrong in this code?
the answer "Welcome mr coffee" is getting print two times.
Posted
Updated 18-Apr-18 16:58pm
v2

Taken that the code you posted is the one you use, as far as I can see, it prints the only once when the password is correct...

However, in the end you print out "Invalid data try again later" even if the data was correct so you may want to use a boolean flag to identify if correct data has been input.

Another thing is that you repeat the question in your code in two places. Why not place it only in the beginning of the loop and test the data after the question.
 
Share this answer
 
You have said to print it twice;

C#
for (int i = 0; i <= 2; i++)


This says,
a) Create a variable named i and set the value to zero.
b) Execute the loop and increment i by 1
c) Do this while i is less than 2

Hence, it completes the loop twice, once for i = 0 & again for i = 1

Kind Regards
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900