Object Arrays in Console Application - c#

I want to create an array of users in a console app but cant seem to get it right, can anyone please help, here is my code.
class Program
{
static void InputUser(User U)
{
Console.WriteLine("Please enter a User:");
Console.WriteLine("User ID:");
U.ID = int.Parse(Console.ReadLine());
Console.WriteLine("Titel:");
U.Titel = Console.ReadLine();
Console.WriteLine("Name:");
U.Name = Console.ReadLine();
Console.WriteLine("Surname:");
U.Surname = Console.ReadLine();
Console.WriteLine("Telephone Number:");
U.Telephone = int.Parse(Console.ReadLine());
Console.WriteLine();
}
static void Main()
{
User[] users = new User[2]
{
InputUser(new User);
}
}
}

First, change the InputUser method to return a User object which will be constructed using the user's input:
static User InputUser()
{
User U = new User();
Console.WriteLine("Please enter a User:");
Console.WriteLine("User ID:");
U.ID = int.Parse(Console.ReadLine());
Console.WriteLine("Titel:");
U.Titel = Console.ReadLine();
Console.WriteLine("Name:");
U.Name = Console.ReadLine();
Console.WriteLine("Surname:");
U.Surname = Console.ReadLine();
Console.WriteLine("Telephone Number:");
U.Telephone = int.Parse(Console.ReadLine());
Console.WriteLine();
return U;
}
And then call the InputUser method two times, since you're initializing an array of User objects with the size of 2:
static void Main()
{
User[] users = new User[2]
{
InputUser(),
InputUser()
}
}

Change your main method to something like:
static void Main()
{
User[] users = new User[2];
for (int i=0;i<users.Length; i++)
{
users[i] = new User();
InputUser(users[i]);
}
}

User[] users = new User[2]
will just create an array of User, but it doesnt initialize them.
For each of them you need to create a User.
So add a loop after it like this:
for (int i=0;i<users.Length; i++)
{
users[i] = InputUser(users[i]);
}

InputUser needs to pass the User object by reference (ref keyword) or it needs to return a new instance of User instead of accepting a parameter.

Related

How to Fix an array and a loop?

I created a User login and password program where a user has to type in a username and a password. I have my usernames and passwords in parallel arrays. If a user types the username or password wrong for the first time they get a message saying "Username is incorrect try again" or "password is incorrect try again".
My problem is if the user types in the wrong username for the first time they get the error message, but if the user type in the right username for the second time they still get the error message.
What I found out is when they get it wrong for the first time the program asks them to input the second username instead of the first one. How can I fix this so the program lets the user type in the first username instead of asking for the second username?
// The available usernames and passwords a user can input
string[] username = {"BUL","GVL","UDF","RFT","WDR" };
int[] password = {100, 200, 300, 400, 500 };
Console.WriteLine("\nUsername,Password \nBUL,100 \nGVL,200 \nUDF,300 \nRFT,400 \nWDR,500 ");
// Loop for Username Input
for (int i = 0; i < username.Length; i++)
{
Console.WriteLine("Enter Username");
string inputUsername = Console.ReadLine();
// if user type a wrong username, they need to try again
if (username[i] != inputUsername)
{
Console.WriteLine("Incorrect Username, Try again");
}
else
break;
}
How about using a Dictionary to store the usernames and passwords as Key-Value-Pairs instead of storing theme in two separate arrays? This way, you can check both username and password in one step.
Dictionary<string, string> dic = new Dictionary<string, string>
{
{ "BUL", "100" },
{ "GVL", "200" },
{ "UDF", "300" },
{ "RFT", "400" },
{ "WDR", "500" }
};
while(true)
{
Console.WriteLine("Enter Username");
string inputUsername = Console.ReadLine();
Console.WriteLine("Enter Password");
string pass = Console.ReadLine();
if (!dic.Contains(new KeyValuePair<string, string>(inputUsername, pass)))
Console.WriteLine("Incorrect Username/password, Try again");
else break;
}
Try this:
bool isUserNameValid = false;
string inputUsername = "";
do
{
Console.WriteLine("Enter Username");
inputUsername = Console.ReadLine();
for ( int i = 0; i < username.Length; i++ )
if ( username[i] == inputUsername )
{
isUserNameValid = true;
break;
}
if ( !isUserNameValid )
Console.WriteLine("Incorrect Username, Try again");
}
while ( !isUserNameValid );
bool isPasswordValid = false;
int inputPassword = 0;
do
{
Console.WriteLine("Enter Password");
int.TryParse(Console.ReadLine(), out inputPassword);
for ( int i = 0; i < password.Length; i++ )
if ( password[i] == inputPassword )
{
isPasswordValid = true;
break;
}
if ( !isPasswordValid )
Console.WriteLine("Incorrect Password, Try again");
}
while ( !isPasswordValid );
If you want to persist using Array, then you could do as the following code. But it would be always better to use Dictionaries in this scenario, which provides you a mapping between UserName and Password. If you were to use Arrays, you would need to map them yourself based on Array Index.
You can employ two loops, each validating the username and then combination of username/password until it is valid.
string inputUserName,inputPassword;
// Loop for Username Input
while(true)
{
Console.WriteLine("Enter Username");
inputUserName = Console.ReadLine();
if(username.Contains(inputUserName))
break;
else
Console.WriteLine("Incorrect UserName");
}
while(true)
{
Console.WriteLine("Enter Password");
inputPassword = Console.ReadLine();
var indexOfUserName = Array.IndexOf(username,inputUserName);
if(Int32.TryParse(inputPassword,out var value) && password[indexOfUserName] == value)
break;
else
Console.WriteLine("Incorrect Password");
}
While using Dictionary you could change the code as follows.
// Dictionary declaration
var userDictionary = new Dictionary<string,int>
{
{ "BUL", 100 },
{ "GVL", 200 },
{ "UDF", 300 },
{ "RFT", 400 },
{ "WDR", 500 }
};
string inputUserName,inputPassword;
// Loop for Username Input
while(true)
{
Console.WriteLine("Enter Username");
inputUserName = Console.ReadLine();
if(userDictionary.Keys.Contains(inputUserName))
break;
else
Console.WriteLine("Incorrect UserName");
}
while(true)
{
Console.WriteLine("Enter Password");
inputPassword = Console.ReadLine();
if(Int32.TryParse(inputPassword,out var value) && userDictionary[inputUserName] == value)
break;
else
Console.WriteLine("Incorrect UserName");
}
If you would like to further eliminate some duplicate code, you could refactor the code as following.
var userDictionary = new Dictionary<string,int>
{
{ "BUL", 100 },
{ "GVL", 200 },
{ "UDF", 300 },
{ "RFT", 400 },
{ "WDR", 500 }
};
Console.WriteLine("\nUsername,Password \nBUL,100 \nGVL,200 \nUDF,300 \nRFT,400 \nWDR,500 ");
var userName = ReadFromUserTillTrue("Enter UserName","Incorrect UserName",x=>userDictionary.Keys.Contains(x));
var password = ReadFromUserTillTrue("Enter Password","Incorrect Password",x=>Int32.TryParse(x,out var value) && userDictionary[userName]== value);
Where ReadFromUserTillTrueis defined as
public string ReadFromUserTillTrue(string promptMessage,string errorMessage,Func<string,bool> validator)
{
var input = string.Empty;
while(true)
{
Console.WriteLine(promptMessage);
input = Console.ReadLine();
if(validator(input))
break;
else
Console.WriteLine(errorMessage);
}
return input;
}
Besides realy great answers in this thread, I'd also recommend to check Polly.NET framework. When I need to do something with retries I find it already has something that serves my needs. Below is an example of how you can implement retries with countdown (and there is many more other nice things in the framework):
var usernames = new List<string>(){ "BUL", "GVL", "UDF", "RFT", "WDR" };
int[] passwords = { 100, 200, 300, 400, 500 };
var user = Policy
.HandleResult<String>(r => !usernames.Contains(r))
.RetryForever((r)=> Console.WriteLine($"Username is incorrect, Try again"))
.Execute(() => {
Console.WriteLine("Enter Username:");
return Console.ReadLine();
});
var expectedPassword = passwords[usernames.IndexOf(user)];
var maxRetries = 5;
Policy
.HandleResult<int>(r => r != expectedPassword)
.Retry(maxRetries, (r, i) => Console.WriteLine($"Password is incorrect. Retries left: {maxRetries - i + 1}"))
.Execute(() => {
Console.WriteLine("Enter Password:");
// should here also be a retry? try do that with Polly :)
int.TryParse(Console.ReadLine(), out var password);
return password;
});

Rover And specimen C#

i am making a simple game of rover, in which i am having a simple problem which i can't figured out
This is my Main Function which is making One rover object in which rover can handle multiple device, there is one device which extract the specimen
Rover rov = new Rover();
string input;
//Device d = new Device();
//Specimen spec = new Specimen();
Console.WriteLine("Welcome to Planetary Rover");
Console.WriteLine("Enter y to start the game or n to exit");
string selection = Console.ReadLine();
if (selection == "y")
{
Console.WriteLine("Enter the rover Default Location X: ");
rov.X =
do
{
Console.WriteLine("Write the device nname to operate ");
input = Console.ReadLine();
rov.Handle(input);
//d.Operate();
} while (input != "end");
}
if (selection == "n")
{
Console.Clear();
}
else
{
Console.WriteLine("Wrong Input!");
}
THe drill is the device which extraxt the specimen whenever it is operated, it only extract if the specimen x and y is equals to rover x and y
I have done these thing but in my drill class there is operate functionwhich is doing the above thing, but problems occurs whenever drill is operating it is again making a new rover, so the rover x and y get null that time, so any can give me a potential fixes for that how can i use the existing rover in the drill function
public override void Operate(string ids)
{
Rover rov = new Rover();
if (specim.X == rov.X && specim.Y == rov.Y)
{
_wearfactor += 5;
Console.WriteLine("specimen extracted and wearfaction of drill is incresed by 5%");
Console.WriteLine(_wearfactor);
_spec. = 0;
}
if(specim.X != rov.X && specim.Y != rov.Y)
{
_wearfactor += 10;
Console.WriteLine("wear factor increased by 10%");
Console.WriteLine(_wearfactor);
}
if (_wearfactor == 100)
{
Console.WriteLine("Drill Destroyed");
Console.WriteLine("syart your program again");
Console.WriteLine("You can not drill specimen now");
this.Name = "";
}
}
You could change your Operate method's signature to:
public override void Operate(Rover rov, string ids)
then when you create Rover rov = new Rover(); you can pass it through for Operate to use.
Operate(rov, "ids");
Another option would be to make a public Rover object and directly reference it through Operate:
// assuming your main class is MainFunction
public class MainFunction()
{
public Rover rov { get; private set; }
public static void Main(string[] args)
{
// Establish the reusable rover
rov = new Rover();
// ...
}
}
Then in Operate, change all rov to MainFunction.rov

how to call String array method in main in c#

I am new to c# and I don't understand why this isn't working. i am getting Error is subjects() in main as mentioned below.
My code is the following:
class Program
{
static void Main(string[] args)
{string sub;
// string brd;
brd = board();
sub = subjects(); // Error
//Console.WriteLine(brd);
Console.WriteLine(sub);
Console.ReadLine();
}
public static string[] subjects()
{
Console.WriteLine("Please Enter How many Subject Do you Want to input");
int limit = System.Convert.ToInt32(Console.ReadLine());
string[] Subjects = new string[limit];
int[] index = new int[limit];
for (limit = 0; limit <= index.Length; limit++)
{
Console.WriteLine("Please Enter Subject Name " + limit + 1);
Subjects[limit] = Console.ReadLine();
}
return Subjects;
}
}
Try this:
string[] sub = subjects();
Instead of this:
string sub;
sub = subjects();
Because you are getting a string of array and passing it to a normal string.
Please refer to /**/ comment
class Program
{
static void Main(string[] args)
{
string sub; /*1. Remove this line*/
// string brd;
brd = board();
sub = subjects(); /*2. string[] sub = subjects();*/
//Console.WriteLine(brd);
Console.WriteLine(sub);
Console.ReadLine();
}
public static string[] subjects()
{
Console.WriteLine("Please Enter How many Subject Do you Want to input");
int limit = System.Convert.ToInt32(Console.ReadLine());
string[] Subjects = new string[limit];
int[] index = new int[limit]; /*3. Remove this line -> Redundant*/
/*4. Change variable `limit` to `i`*/
for (int i = 0; i <= limit; i++)
{
Console.WriteLine("Please Enter Subject Name " + i + 1);
Subjects[i] = Console.ReadLine();
}
return Subjects;
}
}
You are defining sub as string (string sub) but the method subjects is returning a string array. Sosubis not able to hold the return value from that method. you have to change the return type ofsubfrom string tostring[]`. That means the declaration should be like this:
string[] sub = subjects();
Or in much easier way you can make it like this:
var sub = subjects();
So the compiler will automatically choose the return type based on the return value from that method. If you are confused about the datatype in such assignments you can var let compiler decide the datatype based on the values.
Now there is not any Error in the code but in run time error compiler is not printing (sub)
Console.WriteLine(sub);
Console.ReadLine();

Creating lists with loops by an user in C#

So I want to make a list of names. I want this list to go on until user inputs 0 to quit, after user types 0 I want all names to be displayed. You probably see what I'm trying to do from the code below...that "typedName" is there just so you see what I'm trying to do.
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<string> names = new List<string>();
Console.WriteLine("Type in 0 to end.");
bool over = false;
while (over != true)
{
names.Add(Console.ReadLine());
if(typedName == "0")
{
over = true;
}
}
Console.WriteLine("Entered names : ");
names.ForEach(Console.WriteLine);
Console.ReadLine();
}
}
}
First you need the typedName to be captured and then check if it is equal to 0.
if it is not add it to the list
List<string> names = new List<string>();
Console.WriteLine("Type in 0 to end.");
while (true)
{
var typedName = Console.ReadLine();
if (typedName.Equals("0"))
{
break;
}
names.Add(typedName);
}
Console.WriteLine("Entered names : ");
foreach(var name in names)
{
Console.WriteLine(name);
}
Console.ReadLine();
if(typedName == "0")
Well, what is typedName? Or what should it be? I suspect it should be the input entered by the user, something like this:
var typedName = Console.ReadLine();
You can then add it to the list by using that variable:
names.Add(typedName);
And compare it with "0" as you already do, etc.
your code is not complete that is why is not working...
you are missing the most important part:
populate the list if and only if typedName != "0"
while (!over)
{
var typedName =Console.ReadLine();
if(typedName == "0")
{
over = true;
}else
{
Console.WriteLine("Enter a name... ");
names.Add(Console.ReadLine());
}
...
}

using do while statement in method returning string

I am writing a program for shopping system. In this I am using array to get input from the brand name from the user. I am using method which returns string to get the input. Following is code:
public class Brand{
private string brandName;
public string BrandName
{
get { return brandName; }
set { brandName = value; }
}
public string getBrandName()
{
string[] brands = new string[5];
brands[0] = "Honda";
brands[1] = "Suzuki";
brands[2] = "Ferrari";
brands[3] = "BMW";
brands[4] = "Toyota";
Console.WriteLine("Please enter the brand name from the above given brands..");
string temp = Console.ReadLine();
do
{
try
{
for (int i = 0; i < 6; i++)
{
if (brands[i].Contains(temp))
{
this.BrandName = temp;
break;
}
}
return this.BrandName;
}
catch
{
Console.WriteLine("Your provide brand does not match with the database in our system. Please try another one.");
}
} while (BrandName!=temp);
}
}
The problem is that I am at beginner level and not getting the trick what should be in this while statement that it loops and asks user to input again and again until he enters the correct brand name. Please help me.
Maybe this will work based on your code:
public string getBrandName()
{
string[] brands = new string[5];
brands[0] = "Honda";
brands[1] = "Suzuki";
brands[2] = "Ferrari";
brands[3] = "BMW";
brands[4] = "Toyota";
Console.WriteLine("Please enter the brand name from the above given brands..");
string temp = Console.ReadLine();
while(!brand.Contains(temp))
{
Console.WriteLine("Your provide brand does not match with the database in our system. Please try another one.");
temp = Console.ReadLine();
}
return temp;
}
Few things to notice:
We will ask the user for a brand name.
We will check that the input is a brand from brands list (you use contains to check if the input is in the char array of every brand name, watch the difference).
If then name is in the list we will not enter inside the loop and we
will return the brand name.
If the name is not in the list we will ask the user again to insert a
valid brand name until he will enter any and then we will return it.
if you have only 4 no of brands then you can try or statement for all of them in while loop
while (input== 'brand1'||'brand2')
or if your list is too big then you can put them in an arraylist
like this
List <String> listClone = new ArrayList<String>();
for (String string : list) {
if(string.matches("(?i)(bea).*")){
listClone.add(string);
}
}
System.out.println(listClone);
You have an outOfRange exception here :
for (int i = 0; i < 6; i++)
beacuse there is out of range from the array where brands[5].
The function contains return true or false when the input string is substring of the specified string and not equel !!!
You arrive to this row only if has exception:
Console.WriteLine("Your provide brand does not match with the database in our system. Please try another one.");
Check the following code - it work well :
class Program
{
static void Main(string[] args)
{
Brand brand = new Brand();
string brandName = brand.getBrandName();
Console.WriteLine("You enter correct brand name !!!");
Console.WriteLine(brandName);
Console.ReadLine();
}
public class Brand
{
private string brandName;
public string BrandName
{
get { return brandName; }
set { brandName = value; }
}
public string getBrandName()
{
bool isValid = false;
string temp = "";
string[] brands = new string[5];
brands[0] = "Honda";
brands[1] = "Suzuki";
brands[2] = "Ferrari";
brands[3] = "BMW";
brands[4] = "Toyota";
Console.WriteLine("Please enter the brand name from the above given brands..");
while (!isValid)
{
for (int i = 0; i < brands.Length; i++)
{
Console.WriteLine(brands[i]);
}
temp = Console.ReadLine();
for (int i = 0; i < brands.Length; i++)
{
if (brands[i] == temp)
{
this.BrandName = temp;
isValid = true;
break;
}
else
{
isValid = false;
}
if (i == brands.Length - 1)
{
Console.WriteLine("Your provide brand does not match with the database in our system. Please try another one.");
}
}
}
return temp;
}
}
}

Categories