Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have multiple input that need to be validated. Eg:
Enter number of instances:
Enter number of IPv4 available:
Enter number of IPv4 available:
Enter number of IPv6 available:
Enter number of user:
...
Each of these inputs need to be larger than 0. If the input is invalid, the prompt will keep asking. What is the best way to perform that?
I was about to create a boolean variable to for each of them and use while loop to change boolean value to true,... but that would take too long since I have more than 10 input like that.
Thank you and appreciate any helps
Sound like this
class Program
{
static void Main(string[] args)
{
int instances = CheckValues("Number of instances");
int numofIpv4 = CheckValues("number of ipv4");
int numofIpv6 = CheckValues("number of ipv6");
//etc
}
private static int CheckValues(string input)
{
int parserValue = 0;
string enteredValue = string.Empty;
do
{
Console.WriteLine(input);
enteredValue = Console.ReadLine();
}
while (!Int32.TryParse(enteredValue, out parserValue) || parserValue == 0);
return parserValue;
}
}
Here is a simple design in pseudo-code for what you want:
IDictionary<string, int> dict = new Dictionary<string, int>(); // where you would store all
// the answers
String prompt1 = "Enter a number ...";
String prompt2 = "Enter number of IPv4 ..."; // and so on
// initialize your stack
Stack<string> prompts= new Stack<string>();
prompts.Push(prompt1);
prompts.Push(prompt2);
while(prompts.Count != 0){
String prompt = prompts.Peek(); // this doesn't remove the element from stack
int input = 0;
//display prompt to user and get input in input variable
if(input>0){ // or whatever validation logic you want
dict.Add(prompt, input);
prompts.Pop(); //removes topmost element
}
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am adding an option in which new people can be added, who in turn are being entered into a list. This is the relevant snippet:
Console.WriteLine("Enter the persons name");
string _name = Console.ReadLine();
Console.WriteLine("Enter the persons height");
string heightinput = Console.ReadLine();
decimal _height = Convert.ToDecimal(heightinput);
Person personnum = new Person(_name, _height);
_userlist.AddPerson(personnum);
How can I make it so the object name is automatically generated (i.e where personnum is)?
I guess wat you need is either a default value for auto properties like following:
public string Name { get; set;} = "Default Value"
Another option is to define a list with possible values and then retrieve a random value that you assign like following
Random random = new Random();
string[] array = { "Hallo", "OtherValue" };
int randomNumber = random.Next(0, array.Length);
string variableToAssign = array[randomNumber];
I hope this is an approach for you please comment if you need further help!
You can generate random name at every new instance of your object in constructor :
public Person(string _name, double _height)
{
if (string.IsNullOrEmpty(_name)) this._name = GetRandomName();
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
What i want to do is to use something like this Console.Writeline($"Name {Key} - Points: {Value}");
but i dont know how to make the data from the txt into Keys and Values.
I see, you want to fill a Dictionary<string, int> with the names and points of people, right?
If yes then I would suggest never use a dictionary Keys for names, because names are the data that can be duplicate which will eventually lead your software to throw exceptions regarding that.
Make a Generic List of custom class data. Something like this:
public class UserPoint
{
public string Name { get; set; }
public int Points { get; set; }
}
Then like below you can read your text file and load the data into the Generic List.
public static void Main(string[] args)
{
var lines = System.IO.File.ReadAllLines(#"myfile.txt"); // I assume each user info is separated by a newline.
var pointsList = new List<UserPoint>();
foreach(var line in lines)
{
var splittedLine = line.Split(';');
if(splittedLine.Length < 1) continue;
var userPoint = new UserPoint { Name = splittedLine[0].Trim() };
if(splittedLine.Length > 1 && int.TryParse(splittedLine[1].Trim(), out var points)) // updated the direct conversion to safe conversion with tryparse.
{
userPoint.Points = points; // To get rid of extra parsing you can also keep Points property as string.
}
pointsList.Add(userPoint);
}
}
PS: There are multiple other ways to read the text file but I used a simple way, You can also use FileStream and StreamReader classes if you like. Read more on reading text files on these MSDN Articles.
EDIT:
I notice you want to iterate and print through the list as well, you can do in the first loop or you can write a loop again. See:
foreach(var userPoint in pointsList)
{
Console.WriteLine($"Name: {userPoint.Name}, Points: {userPoint.Points}");
}
EDIT 2:
OP has asked to sort the list in descending order based on the points value. Here is a solution for that:
pointsList = pointsList.OrderByDescending(userPoint => userPoint.Points).ToList();
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
so i'm trying to make a program (text based) that can scan a word you type into it to see if it's a palindrome or not so just a true or false outcome i'm a beginner with c# so please help me out!
So far this is all i have done.
//Name space
namespace PalindromeChecker
{
//Class
class Program
{
//Function
static void Main(string[] args)
{
Console.WriteLine("Type the word");
ConsoleKeyInfo Keyinfo = Console.Readkey();
}
}
}
A palindrome is a sequence of characters that is the same whether read forward or in in reverse. So to determine if a string is a palindrome, we can compare the string with its reverse, it is one.
So how can you create a reverse of a string? If you look at the String definition, you'll see it implements IEnumerable. Now the System.Linq namespace offers the IEnumerable.Reverse method. This can be used to reverse a string:
var str = "oxo";
var reversed = str.Reverse();
However, this returns an enumeration of char, not a string. So string.Concat is needed to turn reversed into a string. Having done that, we now have:
var str = "oxo";
var reversed = string.Concat(str.Reverse());
To test if they are the same, simply compare them:
if (str == reversed)
{
// we have a palindrome
}
A "gotcha here is that if str is null, you'll get a null exception with str.Reverse. That can be handled with a null check. So we can then simplify the whole thing down to:
if (str != null && str == string.Concat(str.Reverse()))
{
// we have a palindrome
string word = "hi"; ;
char[] wordArray = word.ToCharArray();
char[] revWordArray = wordArray.Reverse().ToArray();
int count = 0;
for (int i1 = 0; i1 < wordArray.Length; i1++)
{
if (wordArray[i1] == revWordArray[i1])
{
count++;
}
}
if (count == wordArray.Length)
{
bool a = true;
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I am simply very confused and could use some help. I dont really know what is going on with the return of num in numCheck method. My teacher said that it should look how it does now so what was returned and how can I use it? I am trying to make a program that asks for the answer to a math problem (e.g. 2 + 2) and if the users input is 4 it end but anything else it asks again. This should have taken 5 mins, I just dont understand what he meant. Thank you!
namespace readNumber
{
class Program
{
static void Main(string[] args)
{
//should be a loop around this method call
//for(......)
numCheck();
Console.ReadLine();
}
static int numCheck()
{
bool itWorked;
int num;
do
{
Console.Write("Enter a Number: ");
string numSt = Console.ReadLine();
Console.WriteLine(numSt);
itWorked = int.TryParse(numSt, out num);
if (itWorked)
{
Console.WriteLine("Integer assigned: " + num);
}
else
{
Console.WriteLine("It Failed");
}
}
while (!itWorked);
return num;
}
}
}
The error I get most is "the name "num" does not exist in the current context" whenever I try to use num in the main program
I will answer the question :
what was returned and how can I use it?
The returned value num of the method numCheck is simply the number entered by the user, actually the method keeps looping until the user enters a valid number, than it breaks the do-while loop and returns num.
Now, you can use checkNum as it is to acquire numbers from the user.
Example:
Console.WriteLine("What is 2+2 ?");
int ans = checkNum();
if(ans == 4)
{
Console.WriteLine("Yes ! that is correct");
}
else
{
Console.WriteLine("No!, false answer");
}
You have not defined any variable named num in your main.
In order to use the value returned from checkNum() you need to assign it to a variable like in the solution by #chouaib.
your main should be like this
static void Main(string[] args)
{
int num;
//should be a loop around this method call
//for(......)
num = numCheck();
Console.ReadLine();
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I need a way to get the response from a user.
For example they type "hat" and it displays the price in the array table in a console writeline. It also needs to be done in a 2d array instead of dictionary
class Table
{
string[,] names = {
{"rice", "50"},
{"chip", "20"},
{"hat", "50"},
{"ball", "34"},
};
}
class Program
{
static void Main(string[] args)
{
string Res;
Console.WriteLine("What product would you like?");
Res = Console.ReadLine();
Console.ReadKey();
}
}
Use a Dictionary<string, string> rather that way you can look up the Value based on the Key
Dictionary<string, string> example = new Dictionary<string, string>();
example.Add("hat", "50");
//Add the rest in this manner
The you can do the lookup like this
if (example.ContainsKey(Res))
string price = example[Res];
Straightforward solution with 2-d array:
class Program
{
static void Main(string[] args)
{
var products = new[,] { {"rice", "50"}, {"chip", "20"}, {"hat", "50"}, {"ball", "34"} };
Console.WriteLine("What product would you like?");
var request = Console.ReadLine();
string value = null;
if (request != null)
{
for (int i = 0; i < products.GetUpperBound(0); i++)
{
if (products[i, 0] == request)
{
value = products[i, 1];
break;
}
}
}
if (!string.IsNullOrEmpty(value))
{
Console.WriteLine("You've selected: " + request + ". Value is: " + value);
}
else
{
Console.WriteLine("You've selected: " + request + ". No value found.");
}
Console.ReadKey();
}
}
you should be using a Dictionary instead of your jagged array. It is better and you get more flexibility.
var items = new Dictionary<string, string>(5);
items.Add("rice", "50");
items.Add("chip", "20");
// and so on
then you get the item by checking to see if the key exists first:
if (items.ContainsKey("rice"))
{
// it exists! read it:
Console.WriteLine(items["rice"]);
}