I am new to programming and taking my first course, programming fundamentals and on our current homework assignment I have a problem I cannot get.
The problem is- "A bag of cookies holds 40 cookies. The calorie information on the bag claims that there are 10 servings in the bag and that a serving equals 300 calories. Create an application that lets the user enter the number of cookies he or she actually ate and then reports the number of calories consumed."
My form:
The error i get when I run without debugging:
//below is my 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 Calorie_Counter
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int cookies = int.Parse(textBox1.Text);
int calories = (cookies * 75);
textBox2.Text = calories.ToString();
}
}
}
You encounter this problem when using the int.Parse() method. This method simply converts whatever you passed to it as a string to int. So, something like "33" will be converted, but what if you entered something that is clearly not an integer such as "x" or even an empty string?
So, this will be converted to a value of 33 in int type no problem.
int parseResultGood = int.Parse("33");
But this will fail and throw an exception, because, obviously "x" cannot be converted into an integer.
int parseResultBad = int.Parse("x");
Luckily though, C# provides you another method to handle this better, namely, int.TryPrase() method. As the name suggests it tries to parse the value, and converts it into an int only if it is possible and send it back to you in the out parameter while it will return true. If the conversion failed, say, because you passed a non-integer value as a string, it will return false, and the value of the out parameter will be zero. So based on the return value of true/false you can know if the conversion was successful or not, and it won't thrown an exception.
int tryParseResult = 0;
if (int.TryParse("X", out tryParseResult))
{
// Use the converted value
}
else
{
// Display an error message or something similar
}
However, I suggest you learn to debug your program. If you did, you'd have been able to figure out the problem for yourself. The article that was linked to in comments is a great one, please follow it. Good luck!
Related
The program is supposed to look for a string in a line, and if it finds the string, it will make the inserts after meeting the condition inside the textfile. Currently, when I run this program it is now simply giving me a blank console. Previously, I had it just reading all the lines properly and could make inserts only if I remove them first but it messed the indexing up and ultimately did not give me the result I wanted. The logic is fairly straightforward, if you see any problems please share your thoughts. Please and thanks. I am very confused why this is having problems and not working.
using System.IO;
using System.Globalization;
using System.Diagnostics;
using System.Text;
using System.Linq;
using System.Linq.Expressions;
namespace Masker
{
class Program
{
public static void Main(string[] args)
{
Console.WriteLine();
string path = #"\file1.txt";
ReadLines(path)
}
public static void ReadLines(string path)
{
int counter = 0;
var text = new StringBuilder();
foreach (string s in File.ReadAllLines(path))
{
counter += 1;
if (s.Contains("000INDEX"))
{
text.AppendLine(s.Insert(60, "#"));
}
else if (s.Contains("001PRTBNR"))
{
text.AppendLine(s.Insert(60, "#").Insert(119,"#").Insert(120,"#").Insert(121, "#"));
};
text.AppendLine(s);
//Console.Write(text.ToString());
}
Console.Write(text.ToString());
}
}
}
The last two blocks of your if/else statement will never be executed.
If the execution reaches the third check
else if (s.Contains("000INDEX"))
that will always be true. Because if it wasn't, then the first check
if (!s.Contains("000INDEX"))
would have already been true.
But the biggest problem is that if the line contains "000INDEX", your while loop becomes and infinite loop. You never leave it. That is probably the reason why you end up with a blank console.
i have method where i create random number once called from other class. Making delegate and pointing it to that method invokes that method itself and random number is generated. I can't access that method without creating new random number. I want to get that method returned value with delegate. By writing it "Console.WriteLine(some_kind_delegate);" gives me path "Consoleapp8.class+method".
P.S although when i use delegate when comparing his pointed value with other variable answer is correct.
Screenshot in visual studio environment with my comments: https://www.dropbox.com/s/cx6858x5qen7k1p/dayum.PNG?dl=0
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp8
{
abstract class variklis
{
delegate int delegatas();
static int litrazas;
static void Main()
{
Console.WriteLine("serijinis bloko numeris: " + blokas.serijinis_bloko_numeris());
Console.WriteLine("variklio tipas: In-line " + blokas.vidus() + " cilindrai");
Console.WriteLine("stumokliu skaicius: " + stumokliai.stumokliuskaicius);
Console.WriteLine("stumokliu kodas: " + stumokliai.stumokliu_kodas());
Console.Write("galimas variklio litrazas siam automobiliui: ");
int.TryParse(Console.ReadLine(), out litrazas);
litrazui();
}
public static void litrazui()
{
string damm;
delegatas zeta;
zeta = blokas.litrazas;
Console.WriteLine(zeta);
if (zeta() <= litrazas)
{
damm = "variklis tinkamas siam automobiliui";
}
else
{
damm = "variklis netinkamas siam automobiliui";
}
Console.WriteLine(damm);
}
}
}
The problem is due to the Console.WriteLine implicitely converting the delegate to a string, which is Consoleapp8.class+method, instead you need to invoke the function be appending parenthesis to the end of it.
Console.WriteLine(zeta());
And to answer the question in your comment. If you need to store the int that is the return from the delegate you can do apply the same principle from above, by appending parenthesis to invoke the function.
int number = zeta();
I am trying to implement a daily payment system (fake server currency) using a Discord Bot and the discord.Net api wrapper. My code does appear to correctly update that balance and recognize date changes, but it does not seem to remember who has collected their daily payment. Please help. Thanks.
using Discord.Commands;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AmberScript3.Modules
{
public class DailyMoney : ModuleBase<SocketCommandContext>
{
List<string> users = new List<string>();
string currentDate = DateTime.Now.ToString("yyyyMMdd");
[Command("money daily")]
public async Task DailyCash()
{
string author = Context.Message.Author.Username;
if(DateTime.Now.ToString("yyyyMMdd") != currentDate)
{
users.Clear();
}
if(users.Contains(author))
{
await Context.Channel.SendMessageAsync("You have already reclaimed your daily payment!");
}
else
{
users.Add(author);
Random r = new Random();
int seed = r.Next(1000);
double val = Math.Round(r.NextDouble() * seed, 2);
Money.AddBalance(Context.Message.Author.Username, val);
await Context.Channel.SendMessageAsync($"Added ${val} to {author}'s account as a daily payment.");
}
currentDate = DateTime.Now.ToString("yyyyMMdd");
}
}
}`
The DailyMoney class is abstract, and so every instantiated version of it will have different values. I would store things you want to keep between instantiations in text files locally, and then grab them in the code on creation. If you really wanted, you could keep all these values in a separate class, and use Newtonsoft.Json's JsonConvert.SerializeObject and JsonConvert.DeserializeObject to store it. There is lots of documentation for that stuff online. Although, just for one List of Strings, just store it in a text file.
I'm trying to read the static securities definition file from the CME, located at:
ftp://ftp.cmegroup.com/fix/Production/secdef.dat.gz
Since they seem to be standard fix messages, I thought I could use QuickFix to help me read them into C# rather than parsing the file myself. I created a test app that basically does what I want, but I'm having 2 issues:
1) I'm getting a QuickFix exception "Invalid message: Header fields out of order" when forming the message from the string. If I set the "validate" boolean to false, this message disappears and the constructor succeeds, but may be an indicator for the next issue.
2) Upon calling p.Crack, I'm getting the QuickFix exception "QuickFix.UnsupportedMessageType", but there doesn't seem to be any indication of what the message type is that is supposedly unsupported.
Anyway, maybe QuickFix wasn't intended to be used in this way, but any ideas on how to get this to work?
using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using QuickFix;
namespace TestQuickFix
{
class Program : QuickFix.MessageCracker
{
static void Main(string[] args)
{
int count = 0;
string line;
Program p = new Program();
StreamReader file = new StreamReader(#"C:\secdef.dat");
while (((line = file.ReadLine()) != null && count < 10))
{
// ISSUE #1 REQUIRES false 2ND ARG WHEN CREATING THE MESSAGE
Message m = new Message(line, false);
// ISSUE #2 Exception of type 'QuickFix.UnsupportedMessageType' was thrown.
p.Crack(m, new SessionID("beginString", "senderCompID", "targetCompID"));
}
file.Close();
}
public void OnMessage(QuickFix.FIX50.SecurityDefinition secDef, SessionID sessionID)
{
Console.WriteLine(secDef.ToString());
}
}
}
The messages seems to be in FIX50sp2 format, supported by QuickFIX. (Please take a look at the tag 1128=9).
http://www.onixs.biz/fix-dictionary/5.0.SP2/tagNum_1128.html
BUT every single message seems to be not-well formatted. In the header are missed tag 8 (should be the BeginString), and also the tag 56 (TargetCompID), that are mandatory.
Therefore in order to load a single line in a message you must put the "false" parameter to avoid validation.
I suppose the second error is related to the not-well formatted messages.
After emailing the QuickFix listserv with this question, I was able to get enough information to get this to work. Although each line still seems to be malformed for some reason, if I keep validation off, I can get the parser to do exactly what I need it to with the following simplified code:
using System;
using System.IO;
using QuickFix;
using QuickFix.DataDictionary;
namespace TestQuickFix
{
class Program
{
private const int MAX_LINES = 10;
static void Main(string[] args)
{
DataDictionary dd = new QuickFix.DataDictionary.DataDictionary("fix\\FIX50SP2.xml");
StreamReader file = new StreamReader(#"C:\secdef.dat");
int count = 0; string line;
while (((line = file.ReadLine()) != null && count++ < MAX_LINES))
{
QuickFix.FIX50.SecurityDefinition secDef = new QuickFix.FIX50.SecurityDefinition();
secDef.FromString(line, false, dd, dd);
Console.WriteLine(secDef.SecurityDesc);
}
file.Close();
}
}
}
I have an application that gets detailed system information, and I have been able to get the percent of charge remaining but not the percent of the battery itself.
Explanation: As time goes on, the battery slowly gets worse and worse, and some applications, like Dell Support Center on Laptops, display the status of the battery, not the status of the charge, which used to be 100% but now is 90%.
How can I get this value in C# or .NET?
Don't have a laptop to test with, but I'm guessing you could use the WMI class Win32_Battery.
It has two fields that look interesting - DesignCapacity, which tells you
Design capacity of the battery in milliwatt-hours.
and FullChargeCapacity, which has the fascinating note that
Full charge capacity of the battery in milliwatt-hours. Comparison of the value to the DesignCapacity property determines when the battery requires replacement.
So my guess is that you can use WMI to read these two values, and then calculate FullChargeCapacity/DesignCapacity to find the battery health percentage number.
EDIT
Here's a brief example of accessing WMI information using C#. I first added a reference to the System.Management assembly. Then:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
System.Management.ObjectQuery query = new ObjectQuery("Select * FROM Win32_Battery");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
ManagementObjectCollection collection = searcher.Get();
foreach (ManagementObject mo in collection)
{
foreach (PropertyData property in mo.Properties)
{
Console.WriteLine("Property {0}: Value is {1}", property.Name, property.Value);
}
}
}
}
}
Also, note that you are basically running a SQL-like query against WMI, so you can vary that if you want. Windows Management Instrumentation Query Language, or WQL, is what you want to search for to learn more about it.
Also take a look at ahawker's answer, it may end up being more helpful if WMI isn't properly capturing the battery data, as he notes.
It seems that you are looking for the values of FullChargeCapacity, DesignCapacity and CurrentCapacity. As someone who has solved this problem before, let me make a few comments.
The first route normally taken would be through a WMI query (Win32_Battery). However, on the test laptops I ran the WMI query (Win32_Battery) against, which included multiple manufacturers, I consistently ran into the problem of FullChargeCapacity always returning zero. Since that didn't work, I re-wrote my solution using Win32 API and was successfully able to get accurate values that way.
Hopefully, WMI will work for you. However, if you experience the same issues I did, here is a summary of the steps required for Win32API.
Use SetupDiGetClassDevs to get a device handle to the battery (GUID_DEVCLASS_BATTERY).
Use SetupDiEnumDeviceInterfaces to get the device data (SP_DEVICE_INTERFACE_DATA).
Use SetupDiGetDeviceInterfaceDetail to get the device path (SP_DEVICE_INTERFACE_DETAIL_DATA).
Use CreateFile with the device path to get handle to battery.
Use DeviceIoControl with battery handle, IOCTL_BATTERY_QUERY_TAG to retrieve battery query info (BATTERY_QUERY_INFORMATION).
Use DeviceIoControl with battery handle, IOCTL_BATTERY_QUERY_INFORMATION and marshalled structs to to retrieve battery info (BATTERY_INFORMATION).
Also see the Enumerating Battery Devices post on MSDN as I found that quite helpful.
I can post my solution if necessary but with all the native struct definitions, it ends up around 500 lines of code.
Example source code: https://gist.github.com/ahawker/9715872
No need to unnecessary complicate things. Try something like:
using System.Management;
PowerStatus pwr = SystemInformation.PowerStatus;
String strBatteryChargingStatus;
strBatteryChargingStatus = pwr.BatteryChargeStatus.ToString();
MessageBox.Show("battery charge status : " + batterystatus);
String strBatterylife;
strBatterylife = pwr.BatteryLifePercent.ToString();
MessageBox.Show("Battery life: "+batterylife);
In this way you can get all of the battery information.
You can use the System.Windows.Forms.PowerStatus class - http://msdn.microsoft.com/en-us/library/system.windows.forms.powerstatus.aspx
PowerStatus p = SystemInformation.PowerStatus;
int a = (int)(p.BatteryLifePercent * 100);
MessageBox.Show(""+a);
WMI worked for me (tested on 3 notebooks of different brands), but I had to use something like this:
new ManagementObjectSearcher(#"\\localhost\root\wmi",
"Select FullChargedCapacity From BatteryFullChargedCapacity");
// use value of resultingInstance.Properties["FullChargedCapacity"]
new ManagementObjectSearcher(#"\\localhost\root\wmi",
"Select DesignedCapacity From BatteryStaticData");
//use value of resultingInstance2.Properties["DesignedCapacity"]
BatteryChargeStatus.Text = SystemInformation.PowerStatus.BatteryChargeStatus.ToString();
BatteryFullLifetime.Text = SystemInformation.PowerStatus.BatteryFullLifetime.ToString();
BatteryLifePercent.Text = SystemInformation.PowerStatus.BatteryLifePercent.ToString();
BatteryLifeRemaining.Text = SystemInformation.PowerStatus.BatteryLifeRemaining.ToString();
PowerLineStatus.Text = SystemInformation.PowerStatus.PowerLineStatus.ToString();
If you want to perform some operation just convert these string values into the integer.
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 batterie
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
showbattrie();
}
private void Form1_Load(object sender, EventArgs e)
{
}
public void showbattrie()
{
PowerStatus status = SystemInformation.PowerStatus;
textBox1.Text = status.BatteryLifePercent.ToString("P0");
}
}
}
Simple code to get Battery Level in C#
protected void batteryLevel ()
{
var filter = new IntentFilter(Intent.ActionBatteryChanged);
var battery = RegisterReceiver(null, filter);
int level = battery.GetIntExtra(BatteryManager.ExtraLevel, -1);
int scale = battery.GetIntExtra(BatteryManager.ExtraScale, -1);
double level_0_to_100 = Math.Floor (level * 100D / scale);
}