|
Thanks that makes a lot of sense. I can now get the program to compile, but when I click the button to calculate/display I get a message saying "input string was not in a correct format. I think I found the problem string:
while (!inputFile.EndOfStream && index < sales.Length)
I can't seem to fix it though. Any ideas here? Full code for reference:
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.IO;
namespace Total_Sales_Homework
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private double Average(int[] iArray)
{
double total = 0.0;
double average;
for (int index = 0; index < iArray.Length; index++)
{
total += iArray[index];
}
average = (double)total / iArray.Length;
return average;
}
private double Highest(int[] iArray)
{
double highest = iArray[0];
for (int index = 1; index < iArray.Length; index++)
{
if (iArray[index] > highest)
{
highest = iArray[index];
}
}
return highest;
}
private double Lowest(int[] iArray)
{
double lowest = iArray[0];
for (int index = 1; index < iArray.Length; index++)
{
if (iArray[index] < lowest)
{
lowest = iArray[index];
}
}
return lowest;
}
private double Total(double[] iArray)
{
double total = iArray[0];
return total;
}
private void salesButton_Click(object sender, EventArgs e)
{
try
{
double totalSales;
double highestSales;
double lowestSales;
double averageSales;
StreamReader inputFile;
const int SIZE = 6;
int[] sales = new int[SIZE];
int index = 0;
inputFile = File.OpenText("Sales.txt");
while (!inputFile.EndOfStream && index < sales.Length)
{
sales[index] = int.Parse(inputFile.ReadLine());
index++;
}
inputFile.Close();
foreach (int value in sales)
{
salesListBox.Items.Add(value);
}
totalSales = Highest(sales);
highestSales = Highest(sales);
lowestSales = Lowest(sales);
averageSales = Average(sales);
totalSalesLabel.Text = totalSales.ToString("n1");
averageSalesLabel.Text = averageSales.ToString("n1");
highestSalesLabel.Text = highestSales.ToString("n1");
smallestSalesLabel.Text = lowestSales.ToString("n1");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
|
|
|
|
|
That's the wrong line - it doesn't contain anything that tried to convert a value from a string to anything
The line just below does though ... it user int.Parse to try and convert a value.
Which implies that you data is not "just numbers", or at least, not "just integer numbers".
We can't look at that - we don't have any access to your data file. And nor do I want it, either - this is an important thing to learn: Compiling does not mean your code is right!
Think of the development process as writing an email: compiling successfully means that you wrote the email in the right language - English, rather than German for example - not that the email contained the message you wanted to send.
So now you enter the second stage of development (in reality it's the fourth or fifth, but you'll come to the earlier stages later): Testing and Debugging.
Start by looking at what it does do, and how that differs from what you wanted. This is important, because it give you information as to why it's doing it. For example, if a program is intended to let the user enter a number and it doubles it and prints the answer, then if the input / output was like this:
Input Expected output Actual output
1 2 1
2 4 4
3 6 9
4 8 16 Then it's fairly obvious that the problem is with the bit which doubles it - it's not adding itself to itself, or multiplying it by 2, it's multiplying it by itself and returning the square of the input.
So with that, you can look at the code and it's obvious that it's somewhere here:
private int Double(int value)
{
return value * value;
}
Once you have an idea what might be going wrong, start using the debugger to find out why. Put a breakpoint on the first line of the method, and run your app. When it reaches the breakpoint, the debugger will stop, and hand control over to you. You can now run your code line-by-line (called "single stepping") and look at (or even change) variable contents as necessary (heck, you can even change the code and try again if you need to).
Think about what each line in the code should do before you execute it, and compare that to what it actually did when you use the "Step over" button to execute each line in turn. Did it do what you expect? If so, move on to the next line.
If not, why not? How does it differ? Look at the variables and see exactly what they contain.
Hopefully, that should help you locate which part of that code has a problem, and what the problem is.
This is a skill, and it's one which is well worth developing as it helps you in the real world as well as in development. And like all skills, it only improves by use!
Sent from my Amstrad PC 1640
Never throw anything away, Griff
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Hello ,
I have this Json :
[
{
"Created_Datetime": "",
"Id": ,
"Last_Login_Datetime": "",
"Leaves": 5,
"Level": 102,
"Losses": 552,
"MasteryLevel": 39,
"Name": "",
"Personal_Status_Message": "",
"Platform": "",
"RankedConquest": {
"Leaves": 0,
"Losses": 21,
"Name": "Conquest",
"Points": 70,
"PrevRank": 0,
"Rank": 0,
"Rank_Stat_Conquest": null,
"Rank_Stat_Duel": null,
"Rank_Stat_Joust": null,
"Season": 2,
"Tier": 15,
"Trend": 0,
"Wins": 14,
"player_id": null,
"ret_msg": null
},
"Region": "Europe",
"TeamId": 0,
"Team_Name": "",
"Tier_Conquest": 15,
"Total_Achievements": 51,
"Total_Worshippers": 91811438,
"Wins": 604,
"ret_msg": null
}
]
And I can't deserialize it entirely with Newtonsoft
What I have tried:
var player1 = JsonConvert.DeserializeObject<IList<Player>>(Json); But all the information in "RankedConquest" are null
I have a class named Player :
public class Player
{
public string Account_Level { get; set; }
public string ChampionName { get; set; }
...
etc
...
public IList<ChampionRanks> m_championslist;
public class RankedConquest
{
public int Leaves { get; set; }
public int Losses { get; set; }
public string Name { get; set; }
public int Points { get; set; }
public int PrevRank { get; set; }
public int Rank { get; set; }
public int Season { get; set; }
public int Tier { get; set; }
public int Trend { get; set; }
public int Wins { get; set; }
public string ret_msg { get; set; }
}
}
} With wich I can do :
Player player1 = JsonConvert.DeserializeObject<Player>(Json.Substring(1, Json.Length - 2));
Same here all the information in "RankedConquest" are null
After this I renamed "public class RankedConquest" to "public class Ranked" and add to my Player class :
public Ranked RankedConquest { get; set; } Then :
player1.RankedConquest = JsonConvert.DeserializeObject<Player.Ranked>(profile);
Give me this error : Cannot deserialize the current JSON array
modified 27-Oct-18 16:37pm.
|
|
|
|
|
I believe the issue lies in that you have multiple fields in Ranked (formerly RankedConquest) marked as type object . I'm pretty sure Newtonsoft doesn't know how to convert from whatever is in the JSON string to the object field, so either specify a class or a value type.
|
|
|
|
|
Thank you, I edited my code but all the data in player1.RankedConquest are still 0 or null
Edit ------------------------------------------------------------------------------------------
Don't know why but all the code work fine now, thank you
modified 27-Oct-18 16:37pm.
|
|
|
|
|
very odd. if you come up with the reason why, i'd be curious.
|
|
|
|
|
Complete Programming Problem #1, Distance Calculator, on page 337 of the textbook.
(using the "starting out with Visual C#" 4th edition Author tony Gaddis, and using visual studios 2015)
The ADDITIONAL REQUIREMENTS described below MUST also be implemented:
Assume the value of Vehicle Speed in MPH may store whole or floating-point numbers (non-monetary).
Assume the value of Hours Traveled can only store whole numbers.
Prevent data conversion exception for the Vehicle Speed in MPH text box by using the appropriate TryParse method. If the data entered is invalid display an appropriate error message to the user, set the focus back to the text box causing the error, and either clear the text box or select all the data entered into it so that it can be replaced.
Validate the input for the Vehicle Speed in MPH to make sure the data entered is greater than zero and does not exceed 180. If not, display an appropriate error message to the user, set the focus back to the text box causing the error, and either clear the text box or select all the data entered into it so that it can be replaced.
Prevent data conversion exception for the Hours Traveled text box by using the appropriate TryParse method. If the data entered is invalid display an appropriate error message to the user, set the focus back to the text box causing the error, and either clear the text box or select all the data entered into it so that it can be replaced.
Validate the input for Hours Traveled to make sure the data entered is greater than zero and not more than 50. If not, display an appropriate error message to the user, set the focus back to the text box causing the error, and either clear the text box or select all the data entered into it so that it can be replaced.
Implement the following fields:
Total Distance which accumulates the distance for each entry (i.e., as shown in the ListBox control)
Total Hours Traveled which accumulates the hours traveled for each entry (i.e., as entered in the Hours Traveled TextBox control)
Total Trips which counts each entry (i.e., incremented each time the user clicks the Calculate Button control)
Display appropriate output to the ListBox control as shown in the sample input-output document attached.
Display Total Distance as a number with two-decimal places.
Display Total Hours Traveled and Total Trips as a number with no decimal places.
Calculate and display the Average Distance which is the Total Distance divided by the Total Trips (recall, average distance is not an accumulator or counter) formatted as a number with two-decimal places.
The program MUST include standard features of a Windows application including:
Change the default Text property of the form to something descriptive
Appropriate naming conventions for all controls (i.e., buttons, labels, text boxes, list). The standard naming convention is descriptive name including control type using camelCase notation. For example: hoursTraveledTextBox, distanceListBox, totalHoursTraveledLabel, exitButton. The exception is controls not referenced in the code-behind of Form1. For example, Label controls used for descriptive purposes only or PictureBox controls used for aesthetic purposes only.
Calculate, Clear, and Exit buttons with appropriate name and keyboard access key
AcceptButton and CancelButton properties should be appropriately assigned to the Calculate button and Clear button, respectively
Ensure tab order for form is logical
When Clear button is clicked the controls outside of the Summary GroupBox control should be cleared (i.e. using the Clear method or assigning an empty string) and the focus set back to the first TextBox control for entering data. The controls inside the Summary GroupBox control should NOT be cleared (i.e., using the Clear method or assigning an empty string). Do NOT reset the values of the fields to zero.
Appropriate naming conventions and data type declarations for variables and fields.
Remove all unused event handlers from the program code.
|
|
|
|
|
Carefully.
Next!
Sent from my Amstrad PC 1640
Never throw anything away, Griff
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
C#NoobHelpMe wrote: on page 337 of the textbook Start there.
|
|
|
|
|
|
Who needs to read textbooks when CodeProject is free?
|
|
|
|
|
Nobody who uses four question marks together is allowed to read a text book. It's probably a law, like "you can't put anything interesting on TV on a Saturday".
Sent from my Amstrad PC 1640
Never throw anything away, Griff
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
People have been making an assumption (very probably valid) that you want us to write your code for you. That would be doing you a disservice though as the question you ask is "How do I do this assignment????" and that's the question I'm going to answer, even though it's probably not the answer that you were wanting.
What you have here are a set of requirements. Some are explicitly stated and some require you to apply a little bit of problem solving. You start your task by working out what you already know. For instance, you have a vehicle speed and you know that it can store whole or floating point numbers (non-monetary). With a little bit of thought, you realise that the speed property is not going to be a whole number so it can't be a long, short or an int. This doesn't leave you with much in the way of data types so you need to do a little bit of research and find out which data types are available in C# that aren't monetary either.
That's how you solve the problem. By breaking big problems down into little problems. You have all the information you need in this question and the related book, so make use of them.
This space for rent
|
|
|
|
|
Pete O'Hanlon wrote: What you have here are a set of requirements Requirement rarely come in that form, unless we are reverse-engineering. What he has is an exact specification of the properties for the components that the teach desires.
Student does not need knowledge on why those properties exist, or why it would be preferred over the alternative. It is not an assignment, it's a joke.
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
"If you just follow the bacon Eddy, wherever it leads you, then you won't have to think about politics." -- Some Bell.
|
|
|
|
|
Hi experts,
I have a WinForm app, with form that build Background Workers in code.
The trigger is a local timer which kill the current BGW if he finished and create it again.
I need in this specific time (between the kill and create - clear all the resources (mainly - memory).
The app uploading files (each above 100MB) using Arrays & Memory Streams.
without clear the memory - it grows with each file ( 3 files can easily get above 1G)
|
|
|
|
|
There are problems here.
1) If you kill a task, it's dead. It can't be asked to recycle it;s resourced after you kill it as the thread itself is terminated, which automatically recycles the stack. So you have no access to the variables that thread was using! To recycle, you need to tell the thread itself it's not needed and let it handle disposal as necessary before it terminates itself by returning from its startup method.
2) There is no specific Array.Dispose in .NET - which means you have no direct control over when the memory allocated to an array is released, even if you are in the task that created it.
The only way to do this is clumsy: tell the task to die via a semaphore so it can intelligently release what resources it has acquired; then when it is complete call GC.Collect to reclaim all unused memory.
Do note that this will not reduce the memory footprint of your overall application, as memory once allocated to a process is not released back to the OS once it is recycled by the CG.
Sent from my Amstrad PC 1640
Never throw anything away, Griff
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
As Griff explained, you can't have the GC collect "part" of the garbage. There's an easy way to cheat; instead of having the download-code in a BGW, put it inside a complete process (a separate executable). You could report progress easily by writing/reading stdout, and if you terminate the process, all resources for that process are cleaned up.
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
"If you just follow the bacon Eddy, wherever it leads you, then you won't have to think about politics." -- Some Bell.
|
|
|
|
|
I'm facing an issue , while populating data within datagridview control.
If datagridview's scroll bar is present, then it's showing a flickering and the scroll bar is not movable.
I have implemented solutions for handling double buffering, but could n't find any luck.
My working code:
<pre> public RxnDetailSelectionForm()
{
InitializeComponent();
this.ClientSize = Properties.Settings.Default.RxnImportFormSize;
this.groupBoxSelSectionType.Enabled = false;
this.groupBoxSelExptType.Enabled = false;
this.groupBoxSelExptType.Visible = false;
this.radioButtonSameSectionSameExpt.Checked = true;
this.dataGridView1.Focus();
PopulateData();
}
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
cp.ExStyle |= 0x02000000;
return cp;
}
}
public void PopulateData()
{
this.dataGridView1.Rows.Clear();
DataTable dataTable = new DataTable("t");
BindingSource bindingSource = new BindingSource();
for (int i = 0; i < dataGridView1.ColumnCount; ++i)
{
dataTable.Columns.Add(new DataColumn(dataGridView1.Columns[i].Name));
dataGridView1.Columns[i].DataPropertyName = dataGridView1.Columns[i].Name;
}
dataTable.ReadXml("SampleData.xml");
bindingSource.DataSource = dataTable;
dataGridView1.DataSource = bindingSource;
this.dataGridView1.Rows[0].Selected = true;
}
private void RxnDetailSelectionForm_FormClosing(object sender, FormClosingEventArgs e)
{
Properties.Settings.Default.RxnImportFormSize = (sender as Form).ClientSize;
}
private void btnCancel_Click(object sender, EventArgs e)
{
this.Close();
}
|
|
|
|
|
You're using databinding; during the binding-process, the UI will stop responding for a very short time. All applications "flicker" like that when processing a lot, and it is not a problem.
If it is a problem to you and you want to eliminate it, then have your gridview virtualized. That's the "fastest" way to show a DGV and its contents.
How to: Implement Virtual Mode in the Windows Forms DataGridView Control | Microsoft Docs[^]
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
"If you just follow the bacon Eddy, wherever it leads you, then you won't have to think about politics." -- Some Bell.
|
|
|
|
|
Tried
this.dataGridView1.VirtualMode = true; , but did n't work.
|
|
|
|
|
That's correct. It requires a bit more than simply toggeling a boolean.
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
"If you just follow the bacon Eddy, wherever it leads you, then you won't have to think about politics." -- Some Bell.
|
|
|
|
|
|
Thanks, have tried it and didn't help.
|
|
|
|
|
I see the software to charge credit card swipe, samsung pay, ... I want to find out how the swipe card works and write code to get payment information in the software sales. how ? You can share the code for me with.
|
|
|
|
|
Start here: Magnetic stripe card - Wikipedia[^]
Sent from my Amstrad PC 1640
Never throw anything away, Griff
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|