Click here to Skip to main content
15,879,535 members
Please Sign up or sign in to vote.
1.33/5 (3 votes)
See more:
It tells me that "Anders" does not exist in a current context, also that there is an error with the else term? I don't understand why

What I have tried:

using System;
public class login
{
public static void Main()
{
string user;
int pass;
int counter = 0;
do
{
Console.Write("Enter a user: ");
user = (Console.ReadLine());
Console.Write("Enter a password: ");
pass = Convert.ToInt32(Console.ReadLine());
if ((user != Anders) || (pass != 1234))
{
Console.WriteLine("Login Error");
counter++;
}
}
while (((user != "Anders") || (pass != 1234)) && (counter != 3));
if ((user != "Anders") || (pass != 1234));
Console.WriteLine("Logged out!");
else
Console.WriteLine("Login successful");
}
}
Posted
Updated 23-Sep-17 12:01pm

Start with the easy one:
Quote:
there is an error with the else term?
Look at your code closely:
C#
if ((user != "Anders") || (pass != 1234));
See that semicolon?
That ends the if block, so the following statement is executed regardless of the if condition. And because of that, the system can't find an if to match the else and complains.
Remove the semicolon:
C#
if ((user != "Anders") || (pass != 1234))
   {
   Console.WriteLine("Logged out!");
   }
else
   {
   Console.WriteLine("Login successful");
   }
And your error will disappear.
BTW: it's a very good idea to always use curly braces, even when you don't need them - it saves a lot of grief later on if you add a line. With the braces, it's obvious that the line need to be inside them, without? Not so clear and can lead to mistakes.

Other problem:
Quote:
"Anders" does not exist in a current context,
Correct, it doesn't. Again, look at the code:
C#
if ((user != Anders) || (pass != 1234))
Anders is not quoted, so it's a variable name, not a string value. There is no variable called Anders in that method, so the system doesn't know what you mean and complains.
Later on in your code, you use a string:
C#
while (((user != "Anders") || (pass != 1234)) && (counter != 3));
So at a guess, you want to use double quotes around Anders in both cases:
C#
if ((user != "Anders") || (pass != 1234))
 
Share this answer
 
v2
using System;
public class login
{
public static void Main()
{
string user;
int pass;
int counter = 0;



try {

Login:
Console.Write("Enter a user: ");
user = (Console.ReadLine());
Console.Write("Enter a password: ");
pass = Convert.ToInt32(Console.ReadLine());
if ((user != "Anders") || (pass != 1234))
{
Console.WriteLine("Login Error");
counter++;
goto Login;

}
else {
Console.WriteLine("Logged in successfully .. !!")
}

}
catch (Exception ex) {
Console.WriteLine(ex.Message);
}
}
 
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