C# high score in game [closed] - c#

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 5 years ago.
Improve this question
Bassicaly I'm stucked with displaying high scores via listbox by discending order(like 500 to 1). Here is my code, keep in mind that label1 is score in the game, so if anyone may help me please?
{
public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
}
private void Form3_Load(object sender, EventArgs e)
{
label1.Text = Form2.passingText;
StreamWriter q = new StreamWriter("C:\\Users\\BS\\Desktop\\tex.txt", true);
q.WriteLine(label1.Text);
q.Close();
StreamReader sr = new StreamReader("C:\\Users\\BS\\Desktop\\tex.txt");
string g = sr.ReadLine();
while (g != null)
{
listBox1.Items.Add(g);
g = sr.ReadLine();
}
sr.Close();
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
}
}

You can read file as list of lines and then sort it using Linq
So, instead of using SteamReader, try this:
using System.Linq;
//....
List<string> hiscores = File.ReadAllLines("C:\\Users\\BS\\Desktop\\tex.txt").ToList();
hiscores.Sort();
foreach (string s in hiscores)
listBox1.Items.Add(s);
EDIT:
since you have to use StreamReader, here is this approach (but the principle is same):
List<string> hiscores = new List<string>();
StreamReader sr = new StreamReader("C:\\Users\\BS\\Desktop\\tex.txt");
string g = sr.ReadLine();
while (g != null)
{
hiscores.Add(g);
g = sr.ReadLine();
}
sr.Close();
hiscores.Sort();
hiscores.Reverse();
//alternatively, instead of Sort and then reverse, you can do
//hiscores.OrderByDescending(x => x);
foreach(string s in hiscores)
{
listBox1.Items.Add(s);
}

Related

How to store data in datagrid using regex and remove dublicates C# [closed]

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 yesterday.
Improve this question
I need some help please. I need to remove dublicates and use regex when load a list of email adresses in datagrid. Regex must check for syntax email adress to be correct.
Here is my code:
public void StoreEmailToDataGrid(string filePath, DataGridView dataGridView)
{
try
{
var baca = File.ReadLines(filePath);
foreach (var line in baca)
{
var rowIndex = dataGridView.Rows.Add();
dataGridView.Rows[rowIndex].Cells[0].Value = rowIndex + 1;
dataGridView.Rows[rowIndex].Cells[1].Value = line;
}
this.totalRows = dataGridView.Rows.Count;
}
catch (IOException)
{
}
}
private void buttonImportMailist_Click(object sender, EventArgs e)
{
string file = "";
openFileDialog1.Filter = "Text Files|*.txt";
openFileDialog1.Title = "Select Mailist";
openFileDialog1.FileName = file;
DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
if (result == DialogResult.OK) // Test result.
{
file = openFileDialog1.FileName;
try
{
email.StoreEmailToDataGrid(file, dataMailist);
}
catch (IOException)
{
MessageBox.Show(result.ToString());
}
}
}
UPD: Remove dublicates solved
var baca = File.ReadLines(filePath).Distinct().ToArray()
Remain, how to use regex to check correct email adresses.
Solved the problem. Just use regex.ismatch
Regex.IsMatch(strIn, #"^([\w-.]+)#(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.)|(([\w-]+.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(]?)$");

C# My arrays are not populating answers. No matter what it always generates 0's [closed]

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 10 months ago.
Improve this question
I have the .txt file saved in the appropriate folder (to be honest, I have one saved in every single possible folder relating to this code) but no matter what it always populates a bunch of zeros.... Can someone show me where I went wrong?
using System.IO;
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;
namespace WindowsFormsAppSix6AttemptNumber6
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private double[] myArray =
{
1245.67,
1189.55,
1089.72,
1456.88,
2109.34,
1987.55,
1872.36
};
private void analyzeBtn_Click(object sender, EventArgs e)
{
string salesValue;
Double[] sales = new double[8];
int count = 0;
double maxSales = Double.MinValue;
double minSales =Double.MaxValue;
double totalSales = 0;
try
{
StringReader dataStream = new StringReader("Sales.Txt");
salesValue = dataStream.ReadLine();
var total = sales.Sum();
var average = sales.Average();
var high = sales.Max();
var low = sales.Min();
while (salesValue != null)
{
try
{
sales[count] = Convert.ToDouble(salesValue);
totalSales += sales[count];
if (sales[count] > maxSales)
maxSales = sales[count];
if (sales[count] < minSales)
minSales = sales[count];
count++;
}
catch (FormatException)
{
Console.WriteLine("\tException: '" + salesValue + "'");
salesValue = dataStream.ReadLine();
}
dataStream.Close();
for (int item = 0; item < 7; item++)
listBoxLbl.Items.Add(sales[item]);
string listItems = string.Join(",\n", sales);
Console.WriteLine(listItems);
Console.WriteLine(totalSales);
Console.WriteLine(maxSales);
Console.WriteLine(minSales);
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
private void exitBtn_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
below is what it does when i use the analyze button. I have been going in circles with this one and cant figure out what I am doing wrong....
[1]: https://i.stack.imgur.com/OFGgv.png
If that's your intention, you should use "StreamReader".
//StringReader dataStream = new StringReader("Sales.Txt");
StreamReader dataStream = new StreamReader("Sales.Txt");
"sales[count] = Convert.ToDouble(salesValue);"
"salesValue = dataStream.ReadLine();"
"Console.WriteLine(ex);"
Please Put a breakpoint here and test it.
'salesValue' is file name.
breakpoint 'salesValue'

MD5 Comparison not working [duplicate]

This question already has answers here:
Calculate MD5 checksum for a file
(7 answers)
Comparing two byte arrays in .NET
(28 answers)
Closed 6 years ago.
I tried to create a simple little application to make it easier to create the Update files for my main project, by just comparing files in two more or less similar folders and telling me what files are different. But it always gives me the following output when testing two completely similar folders:
C:\Users\there\Desktop\Folder 2\1.txt
C:\Users\there\Desktop\Folder 2\2.txt
My code:
private void FirstFolderBtn_Click(object sender, EventArgs e)
{
using (var fbd = new FolderBrowserDialog())
{
DialogResult result = fbd.ShowDialog();
if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath))
{
FirstFolderTB.Text = fbd.SelectedPath;
}
}
}
private void SecondFolderButton_Click(object sender, EventArgs e)
{
using (var fbd = new FolderBrowserDialog())
{
DialogResult result = fbd.ShowDialog();
if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath))
{
SecondFolderTB.Text = fbd.SelectedPath;
}
}
}
private void CompareBtn_Click(object sender, EventArgs e)
{
foreach(string file in Directory.GetFiles(FirstFolderTB.Text))
{
byte[] storedFileHash;
using (var md5 = MD5.Create())
{
using (var stream = File.OpenRead(file))
{
storedFileHash = md5.ComputeHash(stream);
}
using (var stream = File.OpenRead(file.Replace(FirstFolderTB.Text, SecondFolderTB.Text)))
{
if(storedFileHash != md5.ComputeHash(stream))
{
ResultTB.AppendText(file.Replace(FirstFolderTB.Text, SecondFolderTB.Text) + "\n");
}
}
}
}
}
I think I am just being dumb right now and overseeing some dumb mistake but I would appreciate if someone could help.
Thanks, Jan
Your bytes comparison is wrong
storedFileHash != md5.ComputeHash(stream)
this will compare references not the bytes.
Use SequenceEqual:
if (storedFileHash.SequenceEqual(md5.ComputeHash(stream)) == false) {
ResultTB.AppendText(file.Replace(FirstFolderTB.Text, SecondFolderTB.Text) + "\n");
}
if missing add using System.Linq in the using section

How to read a .CSV file into an array of a class (C#)

I am trying to pull 3 values from a .csv file into an array of class called PizzaOrder. The .csv file was created using the same program. I am having problems figuring out how to insert the values from the .csv into the array of PizzaOrder.
Here is the code of the form so far:
public partial class Form1 : Form
{
PizzaOrder[] pizzaArray = new PizzaOrder[4];
PizzaOrder[] ReadPizzaArray = new PizzaOrder[4];
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//this is just creating the values and inserting into the array
PizzaOrder p1 = new PizzaOrder(12, "Pepperoni", 14.88m);
PizzaOrder p2 = new PizzaOrder(15, "Mushrooms", 15.69m);
PizzaOrder p3 = new PizzaOrder(13, "Bacon", 15.33m);
PizzaOrder p4 = new PizzaOrder(16, "Olives", 17.47m);
pizzaArray[0] = p1;
pizzaArray[1] = p2;
pizzaArray[2] = p3;
pizzaArray[3] = p4;
}
private void btnDisplay_Click(object sender, EventArgs e)
{
//this is just displaying the contents of the array in a listbox
lstOrders.Items.Clear();
for(int loop = 0; loop < pizzaArray.Length; loop++)
{
lstOrders.Items.Add(pizzaArray[loop].ShowOrder());
}
}
private void btnSave_Click(object sender, EventArgs e)
{
//this is where the .csv file is being created and saved to
StreamWriter SavePizza = new StreamWriter("PizzaFile.csv", true);
try
{
for (int loop = 0; loop < pizzaArray.Length; loop++)
{
SavePizza.Write(pizzaArray[loop].ShowOrder()+ Environment.NewLine);
}
}
catch(System.Exception)
{
MessageBox.Show("A file write error has occured...", "File Error");
}
finally
{
SavePizza.Close();
}
}
private void button1_Click(object sender, EventArgs e)
{
//this is where I am attempting to read from the .csv
StreamReader ReadPizza = new StreamReader(File.OpenRead("PizzaFile.csv"));
try
{
string input = ReadPizza.ReadToEnd();
string[] PizzaRead = input.Split(',');
for (int loop2 = 0; loop2 < ReadPizzaArray.Length; loop2++)
{
//this is where I'm trying to insert from the .csv into the array again, where the problem is
ReadPizzaArray[loop2] = (PizzaRead[0], PizzaRead[1], PizzaRead[2]);
}
}
catch(System.Exception)
{
MessageBox.Show("An error occured during the file read...","File Read Error");
}
finally
{
ReadPizza.Close();
}
}
}
The PizzaOrder class accepts an int, sting, and decimal in that order.
The information from the .csv needs to be added as such.
Any information and/guidance would be most appreciated! Thanks!
You will want to create a new PizzaOrder object to do this. Along with that, you will need to convert to the proper data types. Here is example code:
for (int loop2 = 0; loop2 < ReadPizzaArray.Length; loop2++)
{
ReadPizzaArray[loop2] = new PizzaOrder(Convert.ToInt32(PizzaRead[0]), PizzaRead[1].ToString(), Convert.ToDecimal(PizzaRead[3]));
}
Along with this, you should take a look at some coding standards. local variables are usually not capitalized. A List would likely work better than an array, as you don't know how many entries there will be for different CSV files.
In addition to oppassum's answer, it seems like you didn't split your csv by lines before splitting each line by commas.
string input = ReadPizza.ReadToEnd();
string[] lines = input.Split(new[] { Environment.NewLine}, StringSplitOptions.RemoveEmptryEntries);
foreach (string line in lines)
{
string[] PizzaRead = line.Split(',');
//Insert oppassum's answer here...
}
Read the file with File.ReadAllLines(), and use String.Split() and String.Trim():
var lines = File.ReadAllLines("PizzaFile.csv")
List<PizzaOrder> orders = new List<PizzaOrder>();
foreach (var line in lines)
{
var fields = line.Split(',');
PizzaOrder order = new PizzaOrder()
{
Id = Convert.ToInt32(fields[0].Trim());
Type = fields[1].Trim();
// etc.
}
}
var result = orders.ToArray();

Referencing StreamReader in two methods

Quite new to OO so please be kind.
I have created a method which when button1 is clicked, opens a file dialog and reads the contents into a stream reader sr;
public void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
label1.Text = openFileDialog1.FileName;
StreamReader sr = new StreamReader(label1.Text);
String strNumVertices = sr.ReadLine();
label2.Text = strNumVertices;
}
}
The other code runs in the Form1_Paint method.
public void Form1_Paint(object sender, PaintEventArgs e)
perspectiveMatrix = new Gmatrix("perspective");
translationMatrix = new Gmatrix("translation");
scalingMatrix = new Gmatrix("scaling");
perspectiveMatrix.initAsPerspectiveMatrix(300);
scalingMatrix.initAsScalingMatrix(10, 10, 10);
translationMatrix.initAsTranslationMatrix(150, 50, 1200);
String strNumVertices = sr.ReadLine();
label1.Text = strNumVertices;
My question is, How do I reference stream reader sr from the button1_click method in the Form1_paint method?
Word of advice - don't try.
If you do so, you are in danger of having open files/streams all over the place.
I suggest you open a new steam reader in each method (or abstract it away into its own method).
Note:
You should be wrapping the opening of the stream in a using statement, to ensure proper disposal:
using(StreamReader sr = new StreamReader(label1.Text))
{
String strNumVertices = sr.ReadLine();
label2.Text = strNumVertices;
}
Actually, it should be not the best idea to read from the stream during each paint run. Perhaps you'd like to read the value once, store it in the member variable of your form, and access in the paint method?
Unless you expect the file to have changed between the button click and the paint method being called then you shouldn't be reading from the file again anyway.
Reading the file is very expensive in terms of performance compared to storing the result in a field and retreiving it during the paint method. Or visa versa depending what executes first.
Make it a field on the form class. This changes the scope from the method to the entire form. The warnings from the previous post are still valid.
StreamReader sr;
public void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
label1.Text = openFileDialog1.FileName;
sr = new StreamReader(label1.Text);
String strNumVertices = sr.ReadLine();
label2.Text = strNumVertices;
}
}
public void Form1_Paint(object sender, PaintEventArgs e)
perspectiveMatrix = new Gmatrix("perspective");
translationMatrix = new Gmatrix("translation");
scalingMatrix = new Gmatrix("scaling");
perspectiveMatrix.initAsPerspectiveMatrix(300);
scalingMatrix.initAsScalingMatrix(10, 10, 10);
translationMatrix.initAsTranslationMatrix(150, 50, 1200);
if (sr != null) {
String strNumVertices = sr.ReadLine();
label1.Text = strNumVertices;
}
Why not just store the data you've read from the file and re-use it rather than reading the file again? I'm assuming these methods are in the same class (and the same instance of the object), but there are ways around that if that's not true.
private string StrNumVertices { get; set; }
public void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
label1.Text = openFileDialog1.FileName;
StreamReader sr = new StreamReader(label1.Text);
this.StrNumVertices = sr.ReadLine();
label2.Text = this.StrNumVertices;
}
}
public void Form1_Paint(object sender, PaintEventArgs e)
perspectiveMatrix = new Gmatrix("perspective");
translationMatrix = new Gmatrix("translation");
scalingMatrix = new Gmatrix("scaling");
perspectiveMatrix.initAsPerspectiveMatrix(300);
scalingMatrix.initAsScalingMatrix(10, 10, 10);
translationMatrix.initAsTranslationMatrix(150, 50, 1200);
label1.Text = this.StrNumVertices;
...
}
If it's not the same instance of the object, then I'd consider using a Singleton configuration object (or cache) and storing the data there. It really depends, of course, on the scope and lifetime of the data -- does it apply to the whole application or just this instance? The best way, of course, is to make it an instance property like above, and I assume this will work, but if you're recreating the object you will have to use a different technique.
If you really do want to read the file again (because the data is from a different line), you will need to re-use the stream or, again, read all of the data in one go -- if possible -- then iterate through the items you've read internally.

Categories

Resources