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"]);
}
Related
Closed. This question needs debugging details. It is not currently accepting answers.
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.
Closed 5 years ago.
Improve this question
This is what I have so far...
using System;
using System.Collections.Generic;
using System.IO;
class Solution
{
static void Main(String[] args)
{
string testCaseNumber = Console.ReadLine();
string string1 = Console.ReadLine();
string string2 = Console.ReadLine();
List<char> evenIndex1 = new List<char>();
List<char> oddIndex1 = new List<char>();
for (int i = 0; i <= 10000; i++)
{
if (i % 2 == 0)
{
if (i == string1.Length)
{
break;
}
else
{
char even = string1[i];
evenIndex1.Add(even);
}
}
else
{
if(i == string1.Length)
{
break;
}
else
{
char odd = string1[i];
oddIndex1.Add(odd);
}
}
}
Console.Write(evenIndex1);
}
}
I also did a ton and I'm still really stumped. I'm a beginner so there is a lot of things I still don't know.
How do I print to the console the even indexed numbers in C#?
There are so many ways in which you can do it. Here are a few of them:
replace this:
Console.Write(evenIndex1);
with this:
evenIndex1.ForEach(Console.WriteLine); //requires importing -> using System.Linq;
another way:
foreach(var item in evenIndex1) Console.Write(item + " ");
You could also concatenate all the items within the collection using String.Join then print it like this:
Console.Write(string.Join(",", evenIndex1));
further reading on how the methods used work:
String.Join Method
List.ForEach Method
Try this:
Console.WriteLine(string.Join(" ", oddIndex1.ToArray()));
Closed. This question needs debugging details. It is not currently accepting answers.
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.
Closed 7 years ago.
Improve this question
I have declare a dictionary in C#. But I can't access it by foreach.
Dictionary<int,string>dic=new Dictionary<int,string>()
{
{78,"A"},
{81,"B"},
{90, "C"}
}
Now I want to compare its integer value with an other variable(count). If matches then it will give corresponding string value. How can I access the dictionary by for loop??
I have tried like this.
foreach(int p in dic.Value)
{
if(dic.ContainsKey(p)==count)
{
Console.WriteLine(dic.Values(p));
}
}
It's not working. Not finding anything in any site. Help in advance.
I'm unsure what you are actually trying to ask here. However, below is how to loop over the key value pairs of a dictionary using a foreach.
var dic = new Dictionary<int, string>
{
{78, "A"},
{81, "B"},
{90, "C"}
};
//To loop over the key value pairs of a dictionary
foreach (var keyValue in dic)
{
Console.WriteLine("This is the key: {0}",keyValue.Key);
Console.WriteLine("This is the value: {0}", keyValue.Value);
}
However, i think this is what you are looking to do which requires no loop to find if the key is contained in the dictionary.
const int count = 78;
if (dic.ContainsKey(count))
{
Console.WriteLine(dic[count]);
}
else
{
Console.WriteLine("The dictionary does not contain the key: {0}", count);
}
As #john has mentioned in the comments, you can also use Dictionary.TryGetValue to get the value with a specified key as well
string value;
var success = dic.TryGetValue(count, out value);
if (success)
Console.WriteLine("The dictionary value is: {0}", value);
You can iterate using foreach this way:
foreach(KeyValuePair<int, string> pair in dic)
{
if(pair.Key==count)
Console.WriteLine(pair.Value);
}
Try the example.
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
Dictionary<string, int> dictionary =
new Dictionary<string, int>();
dictionary.Add("apple", 1);
dictionary.Add("windows", 5);
// See whether Dictionary contains this string.
if (dictionary.ContainsKey("apple"))
{
int value = dictionary["apple"];
Console.WriteLine(value);
}
// See whether it contains this string.
if (!dictionary.ContainsKey("acorn"))
{
Console.WriteLine(false);
}
}
}
I am trying to make a potential two player program where one user is prompted to enter a question and then prompted to enter the answer to that question both of which will be stored in a two dimensional array. The first player will be able to enter up to 10 questions. After both the question and answer to that question are stored, I would like to then be able to have the second player prompted to answer the questions the first player asked.
Right now I'm stuck at a pretty basic part which is storing the questions and answers in the array.
Here is the code I have so far my first class:
class MakeOwnQuestion
{
string question;
string answer;
string[,] makequestion = new string[10, 2];
public void MakeQuestion(string question, string answer, int index)
{
if (index < makequestion.Length)
{
makequestion[index, 0] = question;
makequestion[index, 1] = answer;
}
}
My second class:
class MakeOwnQuestionUI
{
MakeOwnQuestion newquestion;
public void MainMethod()
{
PopulateArray();
}
void PopulateArray()
{
string question;
string answer;
Console.WriteLine("Enter Your Question: ");
question = Console.ReadLine();
Console.WriteLine("Enter Your Answer: ");
answer = Console.ReadLine();
newquestion.MakeQuestion(question, answer, 0);
Console.WriteLine("Enter Your Question: ");
question = Console.ReadLine();
Console.WriteLine("Enter Your Answer: ");
answer = Console.ReadLine();
newquestion.MakeQuestion(question, answer, 1);
}
}
I keep getting the same error message after the user enters their first answer
"Object reference not set to an instance of an object"
You need to initialize your newquestion instance:
MakeOwnQuestion newquestion = new MakeOwnQuestion();
I'd also recommend you use GetLength rather than Length for a multidimensional array:
if (index < makequestion.GetLength(0))
{
...
}
Or better yet, just a List<T> of some type, e.g. Tuple<string, string>:
class MakeOwnQuestion
{
List<Tuple<string, string>> makequestion = new List<Tuple<string, string>>();
public void MakeQuestion(string question, string answer, int index)
{
makequestion.Add(Tuple.Create(question, answer));
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
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
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Improve this question
i have a following data in 3 sets.
EUR5-002,EUR10-000,
EUR20-001,EUR50-001,
EUR100-001,EUR200-000,
EUR500-000
EUR5-000,EUR10-000,
EUR20-002,EUR50-001,
EUR100-001,EUR200-000,
EUR500-000
EUR5-001,EUR10-001,
EUR20-002,EUR50-001,
EUR100-002,EUR200-003,
EUR500-000
Here EUR - CurrencyID and 5,10,20,50,100,200,500 are currency values. And the values after "-" is no of notes of the corresponding denomination.(EUR5-002, means 2 notes of 5 EUROs)
In my code I have read each set as string and added to List.
I need a logic in C# using regex or someother to add each individual denomination count from all 3 sets of data.
From the above data, I have to get the output as below.
EUR5-003,EUR10-001,
EUR20-005,EUR50-003,
EUR100-004,EUR200-003,
EUR500-000
Code does not handles any errors which can be caused by wrong input format, you can maintain it for yourself.
using System;
using System.Collections.Generic;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var data = new [] {
"EUR5-002,EUR10-000,EUR20-001,EUR50-001,EUR100-001,EUR200-000,EUR500-000",
"EUR5-000,EUR10-000,EUR20-002,EUR50-001,EUR100-001,EUR200-000,EUR500-000",
"EUR5-001,EUR10-001,EUR20-002,EUR50-001,EUR100-002,EUR200-003,EUR500-000"
};
var results = new Dictionary<string, int>();
foreach (var line in data)
{
var entries = line.Split(',');
foreach (var entry in entries)
{
var parts = entry.Split('-');
string key = parts[0];
if (!results.ContainsKey(key))
{
results[key] = 0;
}
results[key] += int.Parse(parts[1]);
}
}
foreach (var result in results)
{
Console.WriteLine(result.Key + "-" + result.Value.ToString("000"));
}
Console.ReadLine();
}
}
}
You can do it this way
//limit is the highest value of currency
int temp=0;
for(int x=1;x<=limit;x++,temp=0)
{
if((temp=parseDenomination(x,input))!=0)
output+=","+"EUR"+x+"-"+temp;
}
//output has your desired output
private static int parseDenomination(int no,String input)
{
return Regex.Matches(input,#"(?<=EUR"+no+#"-)\d+")
.Cast<Match>()
.Select(x=>int.Parse(x.Groups[0].Value))
.ToList()
.Sum();
}
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
}
}