C
C#2y ago
HubTaken

✅ I don't know why this doesn't work.

I am doing the first task of advent of code in C# and I have problem with my code. I am not sure how to solve it and I been at it for about over an hour. my code doesn't set a variable value to 0 when I want it and I don't understand why. the input file is from first task on advent of code.
string[] lines = File.ReadAllLines("C:\\Users\\huber\\Desktop\\AdventOfCode2022\\task1\\task1\\input.txt");

int highestCalories = 0;
int currentCalories =0;

foreach (string line in lines)
{
string linetext ="";
int number = 0;


linetext = line.ToString().Trim();
bool success = int.TryParse(linetext, out number);
if (success)
{
currentCalories += currentCalories + number;
Console.WriteLine(number);
}
else
{
Console.WriteLine("space");
currentCalories = 0;
// I think this is the error. current calories do not get set to 0.
}


if (currentCalories > highestCalories)
{
highestCalories = currentCalories;
}


}

Console.WriteLine("Highest Calories {0}", highestCalories);
Console.ReadLine();
string[] lines = File.ReadAllLines("C:\\Users\\huber\\Desktop\\AdventOfCode2022\\task1\\task1\\input.txt");

int highestCalories = 0;
int currentCalories =0;

foreach (string line in lines)
{
string linetext ="";
int number = 0;


linetext = line.ToString().Trim();
bool success = int.TryParse(linetext, out number);
if (success)
{
currentCalories += currentCalories + number;
Console.WriteLine(number);
}
else
{
Console.WriteLine("space");
currentCalories = 0;
// I think this is the error. current calories do not get set to 0.
}


if (currentCalories > highestCalories)
{
highestCalories = currentCalories;
}


}

Console.WriteLine("Highest Calories {0}", highestCalories);
Console.ReadLine();
13 Replies
Kouhai
Kouhai2y ago
Did you put a breakpoint and saw that currentCalories wasn't set?
HubTaken
HubTaken2y ago
yep. it wasn't being set to 0. the value of currentCalories just keeps being added up.
Kouhai
Kouhai2y ago
So "space" isn't getting printed to the console as well?
HubTaken
HubTaken2y ago
it is being printed.
HubTaken
HubTaken2y ago
Kouhai
Kouhai2y ago
I'm talking about this line Console.WriteLine("space");
HubTaken
HubTaken2y ago
yeah. space is being printed when string input parsing fails.
Kouhai
Kouhai2y ago
Which means currentCalories is getting set to 0 ThumbsUp
HubTaken
HubTaken2y ago
it is getting there but the value of highestCalories is 166752036 which is way too big I figured it out. currentCalories += currentCalories + number; my logic is bad. currentCalories = currentCalories + number;
Kouhai
Kouhai2y ago
Which could be shortened to just currentCalories += number
HubTaken
HubTaken2y ago
thank you for the help. what do I do with this post? delete it or move it to "closed" or something?
Kouhai
Kouhai2y ago
just /close
Accord
Accord2y ago
Closed!