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 10 months ago.
Improve this question
I'm trying to solve https://open.kattis.com/problems/recount in C#. I have my code written but I know I'm missing something but I'm stuck and I've been working on this for a few days. Whenever I try to run my code I receive a runtime error and I know it's because I need to be able to add a user inputted list to convert to a dictionary but I'm not sure how.
Running on .NET 3.1 for school
Here is the code I have currently
namespace Kattis_Solution___Recount
{
class Program
{
static void Main(string[] args)
{
SortedDictionary<string, int> votes = new SortedDictionary<string, int>();
List<string> names = new List<string>();
string name = "";
name = Console.ReadLine();
Console.Write(name);
Console.Write("\n");
int max = 0;
string winner = "";
while (name[0] != '*')
{
if (votes[name] == 0)
{
names.Add(name);
}
votes[name]++;
if (votes[name] > max)
{
max = votes[name];
winner = name;
}
name = Console.ReadLine();
Console.Write(name);
Console.Write("\n");
}
Console.Write(winner);
Console.Write("\n");
for (int i = 1; i < names.Count; i++)
{
if (votes[names[i]] == max && winner != names[i])
{
Console.Write("Runoff!");
Console.Write("\n");
break;
}
}
}
}
}
You cannot do this if the entry isnt there
if (votes[name] == 0) {
names.Add(name);
}
(unlike some other languages - c++ for example)
You need to do
if (!votes.ContainsKey(name)) {
names.Add(name);
votes[name] = 0;
}
See docs here https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.item?view=net-6.0
The value associated with the specified key. If the specified key is not found, a get operation throws a KeyNotFoundException, and a set operation creates a new element with the specified key.
Related
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 1 year ago.
Improve this question
it is a simple timer that starts from a value set by user and counts down to 0
namespace SuperSimpleTimer
{
class Program
{
static void Main(string[] args)
{
//This makes the loop starts from a user inserted value
myTime = int.Parse(Console.ReadLine());
for (int i = myTime; i >= 0; i--)
{
// clears the old value and Writes the new one
//Console.Clear();
Console.WriteLine(i);
}
Console.ReadLine();
}
}
}
The Simplest way would be:
Thread.Sleep(1000);
This should be applied like this:
using System.Threading;
namespace SuperSimpleTimer
{
class Program
{
static void Main(string[] args)
{
//This makes the loop starts from a user inserted value
myTime = int.Parse(Console.ReadLine());
for (int i = myTime; i >= 0; i--)
{
// clears the old value and Writes the new one
//Console.Clear();
Console.WriteLine(i);
Thread.Sleep(1000); //1000(ms) = 1 second
}
Console.ReadLine();
}
}
}
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 4 years ago.
Improve this question
I have a maybe simple problem. When i start program it show "Operator '==' cannot be applied to operands of type 'string' and 'int'. I dont know what to do with it. Thanks for every help.
Here is code:
class Program
{
static bool check(string input_number)
{
for (int i = 0; i < input_number.Length / 2; i++)
if (input_number[i] != input_number[input_number.Length - i - 1])
return false;
return true;
}
static void Main(string[] args)
{
var results = from i in Enumerable.Range(100, 900)
from j in Enumerable.Range(i, 1000 - i)
let k = i * j
where (check(k.ToString() == 1)
orderby k descending
select new { i, j, k };
var highestResult = results.FirstOrDefault();
if (highestResult == null)
Console.WriteLine("There are no palindromes!");
else
Console.WriteLine($"The highest palindrome is {highestResult.i} * {highestResult.j} = {highestResult.k}");
Console.ReadKey();
}
}
You are trying to compare strings (k.ToString() with numbers (1). In your case, I think, you need to do this: where check(k.ToString()) == true).
You can't compare a string and an int directly, due to C#'s strong typing. Instead, you should "convert" the int to a string, using ToString.
edit: or just not call ToString on k?
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 have a class called UserInfo in which there are two properties Name and ID.
class UserInfo
{
public int Id { get; set; }
public string Name { get; set; }
}
and also i have one custom exception class called UserAlreadyLoggedInException which called in my main method when someone try to use the Name which is already taken by someone.
class UserAlreadyLoggedInException : Exception //
{
public UserAlreadyLoggedInException() : base()
{
}
public UserAlreadyLoggedInException(string message) : base(message)
{
}
public UserAlreadyLoggedInException(string message,Exception innerException) : base(message,innerException)
{
}
Here It Is my main method.
try
{
UserInfo[] Ui = new UserInfo[3];
Ui[0] = new UserInfo();
Ui[1] = new UserInfo();
Ui[2] = new UserInfo();
for (int i = 0; i < 3; i++)
{
Ui[i].Id = i;
Console.WriteLine("Please inter the name of " + (i+1) + " user");
if (i == 0)
{
Ui[i].Name = Console.ReadLine();
}
else
{
Ui[i].Name = Console.ReadLine();
if (Ui[i].Name.Equals(Ui[i - 1].Name))
{
throw new UserAlreadyLoggedInException("UserName Has already taken");
}
}
}
}
catch(Exception ex)
{
Console.WriteLine(ex.GetType().Name + ex.Message);
Console.ReadLine();
}
There are 3 objects of UserInfo Class when [0] index object called it directly take input without any logic because it is the first object.
when [1] index called it will go in to else statement because i here is = 1 , so it will take input and compare it with (i-1) which is zero index , if the name is present it will throw an exception.if the name does not match the loop will continue and the i will become 2 this time , and now again it will go towards else statement and take input , but the prob is here .... now it will compare it with (i - 1 ) which is now become [1] index .. so it will compare the name of 2nd index with 1st index , but not with 0 index ....
how can i compare it with all of the indexes ???
You could put your
if (Ui[i].Name.Equals(Ui[i - 1].Name)){
throw ...
}
code into a loop that goes from 0 -> (i - 1).
So you'd have
for (int j = 0; j < i; j++) {
// (if logic from above, but j instead of (i - 1))
}
You can just check the entire array for the name before you assign it to any item. If you add using System.Linq; to your file, you can use the Any() extension method, which returns true if any item in the array matches the condition:
else
{
string name = Console.ReadLine();
// Before assigning the name to any item, see if it already exists
if (Ui.Any(user => user.Name == name))
{
throw new UserAlreadyLoggedInException("UserName Has already taken");
}
// NOW assign the name
Ui[i].Name = name;
}
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 8 years ago.
Improve this question
How can I write a code in C# to find the sum of letters
If A=0;B=1,C=A+B,D=B+C,E=C+D.....
Example CD=1+2=3,
I have tried this way where input is string and output is sum of letter
using System;
public class Test
{
public static (int output1)
public static void Main(string input1)
{
// your code goes here
}
}
An answer without using dictionary list
class Program
{
static void Main(string[] args)
{
string test = "abcdef";
int sum = 0;
foreach (char c in test)
{
int letterNumber = char.ToUpper(c) - 64;
sum += rtnDegint(letterNumber);
}
Console.WriteLine(sum);
}
int rtnDegint(int n)
{
int first = 0, second = 1, next = 0, c;
for (c = 0; c < n; c++)
{
if (c <= 1)
next = c;
else
{
next = first + second;
first = second;
second = next;
}
}
return next;
}
}
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 years ago.
Improve this question
i have code like this
Global.dbCon.Open();
int idQuestion;
kalimatSql = kalimatSql;
Global.reader = Global.riyeder(kalimatSql);
if (Global.reader.HasRows) {
while (Global.reader.Read()) {
idQuestion = Convert.ToInt32(Global.reader.GetValue(0));
//messageBox.Show(idQuestion.ToString()); -->first message box
}
}
//messageBox.Show(idQuestion.ToString()); -->second message box
Global.dbCon.Close();
i don't have problem to display first messagebox, but how to display second messagebox
edited
i try to make code from #rhughes become a function (class) like this following code
Global.dbCon.Open();
List<int> idQuestions = new List<int>();
Global.reader = Global.riyeder(kalimatSql);
if (Global.reader.HasRows) {
while (Global.reader.Read()) {
int idQuestion = Convert.ToInt32(Global.reader.GetValue(0));
idQuestions.Add(idQuestion);
}
}
Global.dbCon.Close();
foreach (int id in idQuestions) {
return id;
}
but it's no work because not all code paths return a value...i wonder how corret way to do it?
Try something like this:
Global.dbCon.Open();
List<int> idQuestions = new List<int>();
kalimatSql = kalimatSql;
Global.reader = Global.riyeder(kalimatSql);
if (Global.reader.HasRows) {
while (Global.reader.Read()) {
int idQuestion = Convert.ToInt32(Global.reader.GetValue(0));
idQuestions.Add(idQuestion);
}
}
Global.dbCon.Close();
foreach (int id in idQuestions)
{
messageBox.Show(id.ToString());
}
What we are doing here is adding all of the question ids into a list and then displaying each of them afterwards.