As a Newbie to C#, I have some code in C#.
The Program is a kind of Daily Money Saving Algorithm!
I'm struggling to produce the output in some alignment way as shown in below image:
Code I have written:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RemainingDaysCalculation
{
internal class DailyMoneySavingMultiplier
{
public static void Main()
{
DateTime currentDate = DateTime.Now;
int daysInYear = DateTime.IsLeapYear(currentDate.Year) ? 366 : 365;
int daysLeftInYear = daysInYear - currentDate.DayOfYear; // Result is in range 0-365.
int finisheddaysCount = daysInYear - daysLeftInYear;
Console.WriteLine("daysLeftInYear is {0}", daysLeftInYear);
Console.WriteLine("finishedDaysCount is {0}",finisheddaysCount);
int savings = (daysInYear * (daysInYear + 1)) - (finisheddaysCount * (finisheddaysCount -1));
Console.WriteLine(savings);
//Case 2:
Console.WriteLine("_________________________________");
Console.WriteLine(" Day No || Daily Saving || Total Saved");
for (int i=1; i <= daysInYear; i++)
{
Console.WriteLine("{0,-10} || {1,-10} || {2,5}", i, (i * 2), (i * (i + 1)));
//Console.Write(i);
//Console.Write(i * 2);
//Console.Write(i * (i + 1));
}
Console.WriteLine("_________________________________");
}
}
}
Output:
Update:
I have tried the 2 ways from the given workarounds in this reference, but i'm getting the exception like
Thanks to #Oliver and #Oleg for pointing me in the right direction and giving me the helping references.
Finally, I figured out this issue using the code below:
using ConsoleTables;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RemainingDaysCalculation
{
internal class DailyMoneySavingMultiplier
{
public static void Main()
{
DateTime currentDate = DateTime.Now;
int daysInYear = DateTime.IsLeapYear(currentDate.Year) ? 366 : 365;
int daysLeftInYear = daysInYear - currentDate.DayOfYear; // Result is in range 0-365.
int finisheddaysCount = daysInYear - daysLeftInYear;
Console.WriteLine("daysLeftInYear is {0}", daysLeftInYear);
Console.WriteLine("finishedDaysCount is {0}",finisheddaysCount);
int savings = (daysInYear * (daysInYear + 1)) - (finisheddaysCount * (finisheddaysCount -1));
Console.WriteLine("Saving Value " +savings);
//Case 2:
Console.WriteLine("_________________________________");
var table = new ConsoleTable("Day No", "Daily Saving", "Total Saved");
for (int i = 1; i <= daysInYear; i++)
{
table.AddRow(i, (i * 2), (i * (i + 1)));
}
table.Write();
Console.ReadKey();
}
}
}
Result:
Related
So I've been trying to make a Luhn-Algorithm what technically should now work but I searched a bit through the Internet and no one uses a Main method so neither do I, but my Questions or more like my Problem is how do I run the code without a Main Method??
Where do I put my Main method?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace LuhnAlgorithm
{
public static class Luhn
{
static bool IsValid(string number)
{
if (string.IsNullOrEmpty(number)) return false;
bool onSecondDigit = false;
int count = 0;
int sum = 0;
for (int i = number.Length - 1; i >= 0; i--)
{
char c = number[i];
if (!char.IsDigit(c))
{
if (c == ' ') continue;
return false;
}
int digit = c - '0';
if (onSecondDigit)
{
digit *= 2;
if (digit > 9) digit -= 9;
}
sum += digit;
count++;
onSecondDigit = !onSecondDigit;
}
return count > 1 && sum % 10 == 0;
}
}
}
You always need an entry point for your application which is the Main method of your program class. Since C#9 you can use top-level-statements in console applications where C# will add a class and Main method for you. So you don't have to implement it but technically it exists.
See https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/program-structure/top-level-statements
You just implemented a class and most code examples don't do more because it is expected that you know how to write a simple C# application where you can use that class.
I have a very small windows form application that calculates the storage cost for a warehouse depending on the amount of deliveries per year and presents the result in form of a chart.
It's doing what it's supposed to do, but there is just one little flaw.
There is 13 columns in the first bit and then there is 12 every other time.
I want it to always be 12.
I've been trying to reorder some lines of code, it looks like it's all ok, I'm probably just missing one line of code but can't figure it out
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace StorageCost
{
public partial class Form1 : Form
{
public static int throughPot = 52000;
public static int weekly = 1000;
public static int weeklyPalletCost = 180;
public static int deliveries = 2;
public int storageCost;
public static int x = 0;
public static int currentPot = throughPot / deliveries;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Calculate();
}
private void Calculate()
{
currentPot = throughPot / deliveries;
storageCost = 0;
x = 0;
chart1.Series[0].Points[0].YValues[0] = currentPot + 4000;
for (int i = 1; i < 51; i++)
{
currentPot -= weekly;
if (x>= 51 / deliveries)
{
x = 0;
currentPot = throughPot / deliveries;
}
chart1.Series[0].Points[i].YValues[0] = currentPot + 4000;
storageCost += currentPot * weeklyPalletCost;
x++;
}
cost.Text = "Total storage cost: £" + storageCost / 100;
chart1.ChartAreas[0].RecalculateAxesScale();
chart1.Update();
}
private void deliveriesUpDown_ValueChanged(object sender, EventArgs e)
{
deliveries = (int)deliveriesUpDown.Value;
Calculate();
}
}
}
this is the full code.
all I need basically is to get the same result in the beginning as from 13th column onwards
any help will be much appreciated.
thanks in advance.
It was because the first column was done outside of the for loop!
after commenting this out
//currentPot = throughPot / deliveries;
//storageCost = 0;
//x = 0;
//chart1.Series[0].Points[0].YValues[0] = currentPot + 4000;
and changing the loop to for (int i = 0; i < 51; i++)
I got it to work as expected.
Thanks #Grimm
I didn't know about this F11, F10 thing. This helped me a lot!
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
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.
Closed 6 years ago.
Improve this question
CS1001 = Identifier Expected
I took a snippet of code from Java that I would like to test in C#. It has a formula for calculating Experience needed to level up in a Video Game project I would like to use. I have just recently began teaching myself code, so converting this was trial and error for me, but I have eliminated the other 13 Errors and this one has me stuck.
Missing an identifier seems like a pretty rudimentary issue but it is also vague and i'm not sure when to begin to research. I have comment where the error occurs.
Any hints?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
float points = 0;
double output = 0; // Output, XP total at level
float minLevel = 2; // First level to Display
int maxLevel = 100; // Last Level to Display
int lvl = 0;
void Main()
{
for (lvl = 1; lvl <= maxLevel; lvl++)
{
points += Math.Floor(lvl + 300 * Math.Pow(2, lvl / 7.)); // Compile Error CS1001 at "));"
if (lvl >= minLevel)
Console.WriteLine("Level " + (lvl) + " - " + output + " EXP");
output = Math.Floor(points / 4);
}
}
}
}
Original JavaScript Code:
<SCRIPT LANGUAGE="JavaScript">
<!--
document.close();
document.open();
document.writeln('Begin JavaScript output:');
document.writeln('<PRE>');
points = 0;
output = 0;
minlevel = 2; // first level to display
maxlevel = 200; // last level to display
for (lvl = 1; lvl <= maxlevel; lvl++)
{
points += Math.floor(lvl + 300 * Math.pow(2, lvl / 7.));
if (lvl >= minlevel)
document.writeln('Level ' + (lvl) + ' - ' + output + ' xp');
output = Math.floor(points / 4);
}
document.writeln('</PRE>');
document.close();
// -->
</SCRIPT>
That doesn't look like the only problem... :)
See inline comments:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
float points = 0;
double output = 0;
float minLevel = 2;
int maxLevel = 100;
int lvl = 0;
void Main() //<-- Bad entry point public static void Main()
{
for (lvl = 1; lvl <= maxLevel; lvl++)
{
points += (float)Math.Floor(lvl + 300 * Math.Pow(2, lvl / 7.)); // <-- You have to explicitly specify the mantissa if you have a '.' is should be 7.0 or 7f
//^--- You also need to cast to a float here because the expression evaluates to a double
if (lvl >= minLevel)
Console.WriteLine("Level " + (lvl) + " - " + output + " EXP");
output = Math.Floor(points / 4);
}
}
}
}
I'm in trouble on a College project.The project needs to be done using c# as a programming language and made in Windows Form like.
The program executes. I know it has flaws but at least i want to know how to get of this error: http://postimg.org/image/gwuzmyc73/ .
For the problem i need to fold a vector using the Divide et Impera.
I need to insert a number from the keyboard n, the generated vector would be like a=(1,2,3,4,5,6,7) and the final elements are 1,3,5,7.
The problem sounds like:
A vector of n elements.We define its folding by overlaping the 2 halfs,if n is odd.The 2 halfs are folded again until de subvector reaches 1 element.Utilize Divide et Impera.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Plierea_Vectorilor
{
public partial class Form1 : Form
{
public int n;
public int i;
public int[] efinal = new int[50];
public string m = new string(new char[50]);
public int Ls, Ld;
public char[] aux = new char[50];
public Form1()
{
InitializeComponent();
}
public void Pliaza(int p,int q)
{
if (p == q)
{
efinal[p] = 1;
}
else
{
if ((q - p + 1) % 2 != 0)
{
Ls = (p + q) / 2 - 1;
}
else
{
Ls = (p + q) / 2;
}
Ld = (p + q) / 2 + 1;
}
Pliaza(p, Ls);
Pliaza(Ld, q);
/*
string ss = Ls.ToString();
string sd = Ld.ToString();
for (i = p; i <= Ls; i++)
{
aux[0] = 'S';
string.Concat(aux, ss);
string.Concat(aux, " ");
string m = aux.ToString();
string.Concat(aux, m[i]);
}
for ( i = Ld; i <= q; i++)
{
aux[0] = 'D';
string.Concat(aux,Ld);
string.Concat(aux, " ");
string m = aux.ToString();
string.Concat(aux, m[i]);
}
*/
}
private void button1_Click(object sender, EventArgs e)
{
Pliaza(1, n);
for (i = 1; i <= n; i++)
{
if (efinal[i]!=0)
{
label2.Text = Convert.ToString(i);
}
}
}
private void label2_Click(object sender, EventArgs e)
{
}
}
}
You're ALWAYS executing the Pliaza function FROM Pliaza. Aren't you missing a finish condition?
The recursive loop must be finished sometime in someway, else you will get that stack overflow.
A StackOverflowException usually means you have uncontrolled recursion going on. Reviewing your code, I see that Pliaza calls itself twice, using different variables ... but there is no path for Pliaza to exit without calling itself. You need some path to let the recursion bottom out. Very likely this would be to add a return; statement after the efinal[p] = 1; line.
I was trying to solve this problem projecteuler,problem125
this is my solution in python(just for understanding the logic)
lim = 10**8
total=0
found= set([])
for start in xrange(1,int(lim**0.5)):
s=start**2
for i in xrange(start+1,int(lim**0.5)):
s += i**2
if s>lim:
break
if str(s) == str(s)[::-1]:
found.add(s)
print sum(found)
the same code I wrote in C# is as follows
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
public static bool isPalindrome(string s)
{
string temp = "";
for (int i=s.Length-1;i>=0;i-=1){temp+=s[i];}
return (temp == s);
}
static void Main(string[] args)
{
int lim = Convert.ToInt32(Math.Pow(10,8));
var found = new HashSet<int>();
for (int start = 1; start < Math.Sqrt(lim); start += 1)
{
int s = start *start;
for (int i = start + 1; start < Math.Sqrt(lim); i += 1)
{
s += i * i;
if (s > lim) { break; }
if (isPalindrome(s.ToString()))
{ found.Add(s); }
}
}
Console.WriteLine(found.Sum());
}
}
}
the code debugs fine until it gives an exception at Console.WriteLine(found.Sum()); (line31). Why can't I find Sum() of the set found
The sum is: 2,906,969,179.
That is 759,485,532 greater than int.MaxValue;
Change int to long in var found = new HashSet<long>(); To handle the value.
You can also use uint however instead of long, however I would recommend using long.