Why can I assign doubles sometimes without value? - c#

I wrote a small WF program which caculates some condensators and the ohmic law. I now want to tidy up a little bit. I ran across a issue where I use 2 doubles which both got assigned the value 0. I can remove the value from the voltage double. But not the current one. And I can't figure out why. Is there anything I am missing? Error Message is CS0165 Use of unassigned local variable 'current' and occurs in the line where the CalcResistance Method gets called
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Kondensator_Ohmsches_Gesetz_Calc
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void calcResistance_Click(object sender, EventArgs e)
{
double voltage;
double current;
bool ok = double.TryParse(textBox1.Text, out voltage) && double.TryParse(textBox2.Text, out current);
if (ok)
{
textBox3.Text = Formulacollection.CalcResistance(voltage, current);
}
else
{
textBox3.Text = "Error Format not found";
}
textBox4.Text = Formulacollection.ConvertMicro(textBox3.Text);
textBox5.Text = Formulacollection.ConvertMilli(textBox3.Text);
textBox6.Text = Formulacollection.ConvertKilo(textBox3.Text);
textBox7.Text = Formulacollection.ConvertMega(textBox3.Text);
}
}
Formulacollection Class works like this:
using System;
using System.Collections.Generic;
using System.Text;
using static System.Math;
using System.Numerics;
using System.Globalization;
namespace Kondensator_Ohmsches_Gesetz_Calc
{
public static class Formulacollection
{
public static string CalcResistance(double voltage, double current)
{
var resistance = voltage / current;
return resistance.ToString();
}
}

The second part won't always be evaluated when you use the && operator. Try to use & instead of it, or set a default value to current when you declare it.

Firstly CS0165 is the error occurs when using the uninitialized variable.
But here the error occurs for the variable current which is initialized correctly. The brief about the error is here
So try the variable initialization globally in the class and then try to compile it.
Then there is a probability of the ok variable holding the value of two TryParse simultaneously, and also replace the && with &.

Related

C# How to increase value in every second and the increment value is based on amount.text file

The IDE is Visual Studio 2010.
I have two text file called total-cost.txt and amount.txt
The file inside look like below:
total-cost.txt
4500000
amount.txt
600
The first text file (total-cost.txt) represents the total cost which will display at textbox(textbox name is totalcost).
A second file (amount.txt) represents the increment value for every second.
I'm trying to display the total of cost from total-cost.txt and auto increase the value in every second that set in the amount.txt
For example:
4500000 after 1 second become 4500600 after 2 second 4501200 and so on.
If I change the amount.txt value from 600 to 700 it become
4500000 after 1 second become 4500700 after 2 second 4501400 and so on.
The value will keep it refresh and display latest total cost only.
The issue is that I already display the total-cost value in textbox but I do not know how to increment a value that set by amount.txt
The coding I have done is in below
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;
using System.IO;
using System.Globalization;
namespace new_countdown
{
public partial class Form1 : Form
{
private string TotalCost;
private int TotalFont;
public Form1()
{
InitializeComponent();
}
private void ReadTotalCostFile()
{
try
{
StreamReader sr = File.OpenText("total-cost.txt");
TotalCost = sr.ReadToEnd();
sr.Close();
}
catch { }
}
private void UpdateDisplay()
{
if (totalcost.Text != TotalCost)
{
totalcost.Text = TotalCost;
}
if (totalcost.Font.Size != TotalFont && TotalFont != 0)
{
this.totalcost.Font = new System.Drawing.Font("Microsoft Sans Serif",(float)TotalFont,System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Point,((byte)(0)));
}
}
private void timer1_Tick(object sender, EventArgs e)
{
UpdateDisplay();
ReadTotalCostFile();
}
}
}
Somehow, I just have done the display total cost in the textbox.
I have no ideas to do for auto-increment.
Have anyone share the idea or solution. I have much appreciated it.
using System;
using System.IO;
private void IncrementInt32ValueInFile(string filePath)
{
var currentFileText = File.ReadAllText(filePath);
if (int.TryParse(currentFileText, out int integerValue))
{
File.WriteAllText(filePath, Convert.ToString(++integerValue));
}
throw new Exception($"Incorrect file content. Path: {filePath}"); // If value in file can't be parsed as integer
}

Parsing a char inside an if c#

So I've got a character called oper, and i'm parsing it's value from a string. In this if statement I'm trying to check if oper's value is " ". I was told single quotes are needed for a char but I'm still not finding success. Thanks!
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 ProjectCalc
{
public partial class Form1 : Form
{
double val1;
double val2;
char oper;
public Form1()
{
InitializeComponent();
}
private void btnEnter_Click(object sender, EventArgs e)
{
if (oper = char.Parse('')) ;
}
}
}
There are some issues with your code. First, you do an assignment operation and not equality (single = vs ==)
Secondly, if you have a string and want to check if one of his characters is space, you could do:
string myString = "This is a string";
foreach (var c in myString) {
if (c == ' ') // <=== Note the space between the single quotes
... do something
}

Where to declare variables in C#

I have created a simple calculator using VS 2013 Pro... and here is the segment of the codes:
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 CalcTwo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string input = string.Empty;
double numb1, numb2, result;
private void button1_Click(object sender, EventArgs e)
{
double.TryParse(textBox1.Text, out numb1);
double.TryParse(textBox2.Text, out numb2);
result = numb1 + numb2;
textBox3.Text = result.ToString();
}
private void button4_Click(object sender, EventArgs e)
{
double.TryParse(textBox1.Text, out numb1);
double.TryParse(textBox2.Text, out numb2);
result = numb1 - numb2;
textBox3.Text = result.ToString();
}
}
}
now the problem I'm facing is, I've got two more buttons for multiplying and dividing, which in turn forces me to copy paste
double.TryParse(textBox1.Text, out numb1);
double.TryParse(textBox2.Text, out numb2);
for each button. I tried to put the codes with the other variables(double numb1, numb2, result) but getting an error...
Here is the screenshots
Pretty new to Visual Studio and C#.
Help is appreciated! :)
The declaration of the variables is fine at the class level. However, in order to reduce the code duplication you can extract that specific functionality into its own method. Something like this perhaps:
private void CaptureValues()
{
double.TryParse(textBox1.Text, out numb1);
double.TryParse(textBox2.Text, out numb2);
}
Then in the handlers:
private void button1_Click(object sender, EventArgs e)
{
CaptureValues();
result = numb1 + numb2;
textBox3.Text = result.ToString();
}
This gives you a convenient place to put additional code. Checking the inputs and displaying a message, for example:
private void CaptureValues()
{
if (!double.TryParse(textBox1.Text, out numb1))
// textBox1 couldn't be parsed, show an error message
if (!double.TryParse(textBox2.Text, out numb2))
// textBox2 couldn't be parsed, show an error message
}
You could even go a step further and put the values into class-level properties. Something like this:
private double Value1
{
get
{
double result;
if (!double.TryParse(textBox1.Text, out result))
throw new Exception("Couldn't parse the first text box!");
return result;
}
}
private double Value2
{
get
{
double result;
if (!double.TryParse(textBox2.Text, out result))
throw new Exception("Couldn't parse the second text box!");
return result;
}
}
With those, you don't need your numb1 or numb2 variables at all, just reference the properties directly:
textBox3.Text = (Value1 + Value2).ToString();
Currently the properties can throw exceptions, so you might want to handle that:
try
{
textBox3.Text = (Value1 + Value2).ToString();
}
catch (Exception ex)
{
// examine what happened with ex and show an error
}
You can throw a more specific Exception type of course, even a custom one. Or you can respond to the error in the properties instead of in the handlers and not use exceptions at all. (There's an argument to be made, and I agree with it, never to use exceptions for normal logic, and this is potentially one of those edge cases. If it's normal logic, don't use exceptions. If it's an exceptional case and the value should never be un-parseable, go ahead and use them. I'd prefer not to in this case, but was just adding it as a possibility.)
There are a lot of options.

How would I be able to use the && operator in string types in C# (Speech Recognition)

I am writing my own speech recognition program in C# with Microsoft's engine and the way I have the program to recognise commands is to read what is already in a text file. The problem with this is, I have to say the command exactly as it is written. For example, if the command is "what is tomorrows date", I cannot say "what's tomorrows date". I have thought of way to get around it and that is to use the Contains method. Here is my code below,
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;
using System.Speech.Recognition;
using System.Speech.Synthesis;
using System.IO;
namespace TestDECA
{
public partial class Form1 : Form
{
SpeechRecognitionEngine _recognizer = new SpeechRecognitionEngine();
SpeechSynthesizer DECA = new SpeechSynthesizer();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
_recognizer.SetInputToDefaultAudioDevice();
_recognizer.LoadGrammar(new Grammar(new GrammarBuilder(new Choices(File.ReadAllLines(#"D:\Luke's Documents\Speech Commands\TestCommands.txt")))));
_recognizer.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(_recongizer_SpeechRecognized);
_recognizer.RecognizeAsync(RecognizeMode.Multiple);
}
void _recongizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
string speech = e.Result.Text;
if (speech.Contains("open" && "fire fox"))
{
System.Diagnostics.Process.Start(#"D:\Program Files (x86)\Mozilla Firefox\firefox.exe");
}
}
}
}
As you can see, I want to check if speech contains the words "open" and "fire fox". However, Visual Studio gives me an error saying that the && operator cannot be applied to strings. Is there a way of checking the text to see if contains those words or not? Any help at all will be appreciated.
The String.Contains() method takes a single string. "open" && "fire fox" does not evaluate to a string. If you want to check if a string contains two different values, do this:
if (speech.Contains("open") && speech.Contains("fire fox"))
{
...
}
You could create an extension method to help make this easier:
public static bool ContainsAll(this string str, params string[] values)
{
foreach (var value in values)
{
if (!str.Contains(value)) return false;
}
return true;
}
And then use it like this:
if (speech.ContainsAll("open", "fire fox"))
{
...
}

Listing integers from a text file into a listview

I'm creating an app in winforms c# using vs 2013.
In the app I have a textfile to which I'm saying the time in int format using a custom format from a time select dropdown list.
I then want to display what is in that text file on a selectable listview from where I can remove it from the textfile etc. I'm almost there however at the moment when I try to add the items into the listbox they do seem to add however they do not display correctly.
For example say in my text file there is
22102210
19101610
17182218
10272227
Then that is how it should be displayed in the listview as selectable ready to be deleted.
At the moment it isn't showing correctly, it's showing up as 1.. 2.. 1..
Could someone help me out and point me in the right direction as to why this might be happening? Any help much appreciated. This is my class.
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 Chronos
{
public partial class Interface : Form
{
private string[] getTimes = System.IO.File.ReadAllLines(#"G:\Dropbox\University\Chronos\Application\Chronos\Chronos\AdminAccount\Times.txt");
public Interface()
{
InitializeComponent();
}
private void Interface_Load(object sender, EventArgs e)
{
PopulateList();
}
private void PopulateList()
{
int size = getTimes.Length;
lstTime.Items.Clear();
GetTimes();
for (int i = 0; i < size; i++)
{
lstTime.Items.Add(getTimes[i]);
}
}
private void GetTimes()
{
string[] getTimes = System.IO.File.ReadAllLines(#"G:\Dropbox\University\Chronos\Application\Chronos\Chronos\AdminAccount\Times.txt");
}
private void btnAdd_Click(object sender, EventArgs e)
{
string time = pickerTimeStart.Value.Hour.ToString() + pickerTimeStart.Value.Minute.ToString() + pickerTimeEnd.Value.Hour.ToString() + pickerTimeEnd.Value.Minute.ToString();
System.IO.File.AppendAllText(#"G:\Dropbox\University\Chronos\Application\Chronos\Chronos\AdminAccount\Times.txt", time + Environment.NewLine);
PopulateList();
MessageBox.Show("Time added", "Ok");
//PopulateList();
}
}
}
As currently written, GetTimes does nothing except read the file:
private void GetTimes()
{
// "string[]" here overrides the outer scope
string[] getTimes = System.IO.File.ReadAllLines(#"G:\Dropbox\University\Chronos\Application\Chronos\Chronos\AdminAccount\Times.txt");
}
If you change it to this, it becomes more useful:
private string[] GetTimes()
{
return File.ReadAllLines(#"G:\Dropbox\University\Chronos\Application\Chronos\Chronos\AdminAccount\Times.txt");
}
... and then PopulateList can simply become:
lstTime.Items.Clear(); //so you aren't getting a bunch of dupes
lstTime.Items.AddRange(GetTimes().Select(t => new ListViewItem(t)).ToArray());
You can also remove this line because you don't need to keep a copy of the data in the class:
private string[] getTimes = ...
Note: If you decide to keep the data source local and not work solely against the file, much of this would change.

Categories