using List for first names [closed] - c#

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 6 years ago.
Improve this question
I am getting errors on my first names and other areas and I don't know if it is a basic logic error or my concept. In my PromptName() it seems to be not returing anything along with my Display(index, searchedName);
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Seven
{
class Seven
{
static void Main(string[] args)
{
// IMPORTANT CODE REQUIREMENT: In the following list declaration,
// the order of the items in firstNames
// cannot be "manually" changed.
// ------------------------------------------------
List<string> firstNames = { "Johnny", "Alice", "Cory",
"Steve", "Dennis" };
// ------------------------------------------------
int index;
string searchedName = PromptName();
while (searchedName.Equals("end"))
{
index = firstNames.BinarySearch(serchedName);
Display(index, searchedName);
}
Console.Read();
}
private void Display(int index, string name)
{
Console.WriteLine();
if (index >= 0)
{
Console.WriteLine("Yes, {0} is in our course.", searchedName);
}
else
{
Console.WriteLine("No, {0} is not in our course.", name);
}
Console.Write("");
}
private string PromptName()
{
Console.Write("To terminate the program, enter 'end' for the student name.");
Console.Write("Enter the first name of the student to be searched in our course: ");
return Console.ReadLine();
}
}
}

Your while loop does not execute unless PromptName() does return "end".
Change
while (searchedName.Equals("end"))
to
while (!searchedName.Equals("end"))
You have an additional problem that you do not prompt for a new name again. Do that at the end of your while loop, right after your call to Display().
This is the type of problem that is easily resolved with a debugger. If you have not yet learned how to use one in your environment, I would suggest prioritizing it. The time you invest in learning to debug will quickly pay for itself.
UPDATE
I just noticed that your list is not declared properly. It should be
List<string> firstNames = new List<string>() { "Johnny", "Alice", "Cory",
"Steve", "Dennis" };

You may already know this, but on line 25 there is a typo:
Line 25: index = firstNames.BinarySearch(serchedName);
serchedName should be searchedName

Related

How to check more than one value from dictionary in an if statement? [closed]

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 9 months ago.
Improve this question
Im just starting to learn unity and saw this task in one of my c# studying books. I have to create a code using an if statement inside foreach, so that it checks if i can afford each item in the dictionary, but i have no idea how to check all of them or even once specific, so i could write if 3 times for example.
At the moment my Log shows all the items and thier values, but shows if i can afford only the first one. What should i put in the IF brackets to check every value after it appears it Log?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LearningCurve : MonoBehaviour
{
public int currentGold = 3;
void Start()
{
Dictionary<string, int> itemInventory = new Dictionary<string, int>()
{
{"Potions", 4 },
{"Daggers", 3 },
{"Lockpicks", 1 }
};
foreach (KeyValuePair<string, int> itemCost in itemInventory)
{
Debug.LogFormat("Item {0} - {1}g", itemCost.Key, itemCost.Value);
if (currentGold >= itemCost.Value)
{
Debug.Log("I can afford that!");
}
}
}
I am not sure if I understood the question but I will try to give you a basic overview of what is happening in the code you posted.
Let's start with the if, how an if block works is simple you put a boolean bool for short in C# that can have two different values true and a false, inside the if(BOOL VALUE) and if the value is true it will run the code between the { CODE TO RUN }.
Let's refactor the code a bit to see what is going on here.
Dictionary<string, int> itemInventory = new Dictionary<string, int>()
{
{"Potions", 4 },
{"Daggers", 3 },
{"Lockpicks", 1 }
};
foreach (KeyValuePair<string, int> itemCost in itemInventory)
{
Debug.LogFormat("Item {0} - {1}g", itemCost.Key, itemCost.Value);
bool iCanBuyitem = currentGold >= itemCost.Value;
Debug.LogFormat("{0} >= {1} is {2}", currentGold, itemCost.Value,iCanBuyitem);
if (iCanBuyitem)
{
Debug.LogFormat("I can buy {0} ", itemCost.Key);
}else
{
Debug.LogFormat("I can't buy {0} ", itemCost.Key);
}
}
Unlike in mathematics in programing symbol >= is not an equality symbol but something called a binary operator that takes two variables of one of the many numeric types in c# in your dictionary they are integers Dictionary<string, int> and produce a bool value that tells you if one number is more or equal to a second number, it's a method that has something similar to the the following signature public bool FirstIsBiggerOrEqualToSecond(int first, int second)
Here is a dotnet fiddle demonstrating the output https://dotnetfiddle.net/oWlYlY
Read the question header You mean, if you want to put two or more conditions inside the IF, you have to use && operator:
if (currentGold >= itemCost.Value && currentGold <= 15)
{
Debug.Log("I have enough gold to buy this item and it's cheap.");
}
Testing the code snippet provided two logs within the Console: "I can afford that!". Through this, I have determined that the issue lies within your snippet implementation. I suggest you check if you have enabled Collapse within the Console.
I have attached an Imgur link for reference.
Console Log

How do I add 1 number to a array? [duplicate]

This question already has answers here:
Add new item in existing array in c#.net
(20 answers)
Closed 1 year ago.
I do not have anything other than the normal
using System;
namespace TryStuff
{
class Program
{
static void Main(string[] args)
{
}
}
}
And I know that having nothing at the start and still asking questions isnt highly looked on but STILL...
Im trying to create a code that asks you for an integer, and if you answer anything over 0, it ADDS the given number to an array, once you stop giving numbers (example type some "stop") it prints out ALL the numbers given to the array.
I DO NOT need the full code for something like this, just an answer to how do I append to an array without making it insanely complicated (things ive found on the google are like 20 lines of code but im pretty sure its not that hard).
Sorry for the long post and in short, how do I append to an array? If you can provide me a code, please implement it in the C# code or give me a "explanation" how to do it. Thank you very much!
You probably don't want to use an array, you want a different data structure that allows easy expansion, like List<T>. For List<T>, you simply call .Add, like:
using System;
using System.Collections.Generic;
namespace TryStuff
{
class Program
{
static void Main(string[] args)
{
var myList = new List<int>();
while(int.TryParse(Console.ReadLine(), out int x))
{
if (x > 0)
{
myList.Add(x);
}
}
Console.WriteLine("You entered: " + string.Join(",", myList));
}
}
}
This should keep allowing you to enter integer numbers and add them to the list if the number is greater than 0. It ignores all numbers 0 or less than 0. If you type anything that is not a number, it will stop and print out the list you entered.

How to make an app that gives me name by writing the ID [closed]

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 5 years ago.
Improve this question
I need to make a console app using arrays
I have to declare an array with few names and another array with few IDs  and then I have to make the app
to ask me write  the ID and it displays the name of the current ID (0 positioned name has 0 positioned ID and so on)
and if the typed ID is not correct I need to get an answer that the ID doesn't exist also I loops should be used to know which ID goes to which name
ok here is the code and I Don't know what to do more
{fak y'all for downvoting}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp10
{
class Program
{
static void Main(string[] args)
{
string[] names ={ "Endrit", "Endrit1", "Endrit2", "Endrit3", "Endrit4", "Endrit5", "Endrit6" };
string[] ID = { "001", "002", "003", "004", "005", "006", "007" };
Console.Write("Type the ID :");
string IDN = Console.ReadLine();
Console.ReadKey();
}
}
}
You can use Array.IndexOf to get the index of a particular item in an array. If the item is not found, it will return -1.
So, you can just find the index of the user input in the ID array, and return the item at the same index in the names array:
// Get the index in the ID array of the item the user entered
int indexOfUserEntry = Array.IndexOf(ID, IDN);
// If the item was found (index is > -1) show the item at the same index in the names array
if (indexOfUserEntry > -1)
{
Console.WriteLine("The name for that id is: " + names[indexOfUserEntry]);
}
else
{
Console.WriteLine("The specified Id does not exist");
}
Console.WriteLine("\nDone!\nPress any key to exit...");
Console.ReadKey();

How do I print to the console the even indexed numbers in C#? [closed]

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()));

Calculating unique words in a string [closed]

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 8 years ago.
Improve this question
I have a page called post summary.
Under this page, I want to count the total number of words and total number of unique words.
I managed to count the total number of words in the post successfully.
However, I do not know how I can count the unique words.
Eg: "I enjoyed school today very much."
Expected output:
Total word count: 6
Unique word count: 5
Here is my current code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace empTRUST
{
public partial class PostSummary : Form
{
string target_fbid;
string fbStatus;
public PostSummary(string target_fbid, string fbStatus)
{
InitializeComponent();
this.target_fbid = target_fbid;
this.fbStatus = fbStatus;
}
private void PostSummary_Load(object sender, EventArgs e)
{
label_totalwordcount.Text = fbStatus.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries).Length.ToString();
}
}
}
I don't understand your example since there are no repeating words in "I enjoyed school today very much". However, this is a naive approach which might work for you:
var allWords = text.Split();
int count = allWords.Length; // 6
int unqiueCount = allWords.Distinct().Count(); // 6
It is naive because punctuation characters modify the result. So you might want to replace them in the first step:
var allWords = text.ToUpperInvariant().Replace(".", "").Replace(",","").Split(); // ...
Also, the case modifies the result, so you could compare case-insensitively if that is desired.
Can use something like this:
"I enjoyed school school today very much.".Split(' ').Distinct()
This one returns 6, even if there is "school" word that appears 2 times.
EDIT
if you need some custom comparison logic (say case insensitive) you may use Distinct overload where you can specify custom equality comparer.
The first tought is:
public int GetUniqueWordsCount(string input)
{
return input.Split(' ').GroupBy(s => s).Count();
}
If you would like a case insensitive solution you could add .ToLower() or .ToUpper() conversion to your group key selector. Also you may implement your own IEqualityComparer if you want some custom comparsion logic.

Categories

Resources