I am trying to get the output of "1111111111".
The Message function is called by AddMessage and it stores the message into an array.
However when i output the array values, I get the address instead of the value. How do i fix this?
class Program
{
public delegate int print();
public static void Main()
{
print[] array1 = new print[10];
AddMessage(ref array1, Message);
for (int i = 0; i < 10; i++)
{
Console.WriteLine(array1[i]);
}
}
public static void AddMessage(ref print[] array, print msg)
{
for(int i =0; i< 10; i++)
{
array[i] = msg;
}
}
public static int Message()
{
int msg;
msg = 1;
return msg;
}
}
}
A delegate is a function, you're passing a reference to the function itself (not the result) into Console.WriteLine.
Console.WriteLine(array1[i]);
must turn into
Console.WriteLine(array1[i]());
You're printing the object name because you're not calling the delegate:
for (int i = 0; i < 10; i++)
{
Console.WriteLine(array1[i]);
}
You should change this to array1[i]()
Related
I dont really know why i get the Error on the Proccessing line.
I get the error on public static net_events.net_event net_event_proccess(net_events.net_event main)
makes to me no sense because i defined all namespaces.
namespace net_events
{
class net_event
{
public string event_name;
public object[] args;
public void add(object mm)
{
object[] bkk = args;
args = new object[args.Length + 1];
for (int i = 0; i < bkk.Length; i++)
args[i] = bkk[i];
args[args.Length] = mm;
}
public Action procc;
public net_event(string eve, Action proc)
{
event_name = eve;
procc = proc;
}
public net_event()
{
}
}
class net_event_proccess
{
private static List<net_events.net_event> events = new List<net_events.net_event>();
public static net_events.net_event net_event_proccess(net_events.net_event main)
{
for (int i = 0; i < events.Count; i++)
if (events.ElementAt(i).event_name == main.event_name)
return events.ElementAt(i);
return main;
}
}
}
So I am using a GUI with a class. I have done it before and I know most of the time you create an event for a button. Then when that button is pushed, you can create a new object. In this project I am working on, I have a TextBox that I type a name and a score into. Then when I hit the enter button that I have, I want to create a new object with the parameterized constructor and place the name and score in different arrays so I can manipulate them. Then I want to produce the highest, lowest, and avg scores. I have had previous projects where I just create a new object when the button is pressed. But with this I am loading in multiple things in the same TextBox. So every time the button was hit I was creating a new object. What I want to do is create the object once with a parameterized constructor and then add the names and scores to arrays within the class. Any suggestions.
The bottom method in my form class I tried to mess around and do it this way, but it wouldn't do anything.
private void nameTextBox_TextChanged(object sender, EventArgs e)
{
//Get the information from the text box and store it in a variable
string userInput = nameTextBox.Text;
//Create a new object with the parameterized constructor
myBowlingTeam = new BowlingTeam(userInput);
}
PLEASE HELP. This is like my only hiccup. If I get this part to work right the program will work. Cause I know how to work with the class to produce the results I want. Thanks in advance.
Here is my class code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Project_9
{
class BowlingTeam
{
const int MAX = 10;
//local variables
int sizeOfName = 0;
int sizeOfScore = 0;
//Declare Private Data Members
private string nameAndScore = "";
private string name = "";
private int score = 0;
private string[] nameArray = new string[MAX];
private int[] scoreArray = new int[MAX];
private string[] nameAndScoreArray = new string[MAX];
//Default Constructor
//Purpose: To set the initial values of an object
//Parameters: None
//Returns: Nothing
public BowlingTeam()
{
nameAndScore = "";
name = "";
score = 0;
for(int i = 0; i < MAX; i++)
{
nameArray[i] = "";
}
for(int i = 0; i < MAX; i++)
{
scoreArray[i] = 0;
}
for (int i = 0; i < MAX; i++)
{
nameAndScoreArray[i] = "";
}
}
//Parameterized Constructor
//Purpose: To set the values of an object
//Parameters: None
//Returns: Nothing
public BowlingTeam(string aString)
{
nameAndScore = aString;
name = "";
score = 0;
for (int i = 0; i < MAX; i++)
{
nameArray[i] = "";
}
for (int i = 0; i < MAX; i++)
{
scoreArray[i] = 0;
}
for (int i = 0; i < MAX; i++)
{
nameAndScoreArray[i] = "";
}
}
//Split the Input Method
//Purpose: To Split up the data in the array
//Parameters: An array of strings
//Returns: Nothing
public void SplitAndDisperseArray()
{
nameAndScoreArray = nameAndScore.Split();
name = nameAndScoreArray[0];
score = int.Parse(nameAndScoreArray[1]);
//Place the name and the score in their one arrays
PlaceInNameArray(name);
PlaceInScoreArray(score);
}
//Find Highest Score Method
//Purpose: To find the highest score
//Parameters: An array of int
//Returns: An int
public int CalcHighestScore()
{
int highestScore = 0;
int size = 0;
for (int i = 0; i < MAX; i++ )
{
if (scoreArray[i] < scoreArray[i + 1])
{
highestScore = scoreArray[i];
}
else
{
highestScore = scoreArray[i + 1];
}
}
return highestScore;
}
//Find Lowest Score Method
//Purpose: To find the lowest score
//Parameters: An array of int
//Returns: An int
public int CalcLowestScore(int[] anArrayOfInts, int sizeOfArray)
{
int lowestScore = 0;
while (sizeOfArray < MAX)
{
if (anArrayOfInts[sizeOfArray] < anArrayOfInts[sizeOfArray + 1])
{
lowestScore = anArrayOfInts[sizeOfArray];
}
else
{
lowestScore = anArrayOfInts[sizeOfArray + 1];
}
}
return lowestScore;
}
//Calulate Avg. Score Method
//Purpose: To calculate the avg score
//Parameters: An array of int
//Returns: An double
public double CalculateAvgScore(int[] anArrayOfInts, int sizeOfArray)
{
int sum = 0;
double avg = 0;
//Add up all of the elements in the array
while(sizeOfArray < MAX)
{
sum += anArrayOfInts[sizeOfArray];
}
//Divide the sum by the size of the array
return avg /= sum;
}
//Set Score Array Method
//Purpose: To put scores in the score array
//Parameters: An int
//Returns: Nothing
public void PlaceInScoreArray(int aScore)
{
scoreArray[sizeOfScore] = score;
sizeOfScore++;
}
//Set Name Array Method
//Purpose: To put names in the names array
//Parameters: A string
//Returns: Nothing
public void PlaceInNameArray(string aName)
{
nameArray[sizeOfName] = name;
sizeOfName++;
}
}
}
Here is my Form1 code for the GUI:
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 Project_9
{
public partial class Form1 : Form
{
//Declare a reference variable to the class
private BowlingTeam myBowlingTeam;
public Form1()
{
InitializeComponent();
myBowlingTeam = new BowlingTeam();//Create a BowlingTeam object with the default constructor
}
//ExitToolStripMenuItem1_Click
//Purpose: To close the application when clicked
//Parameters: The sending object and the event arguments
//Returns: nothing
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
//AboutToolStripMenuItem1_Click
//Purpose: To display student information
//Parameters: The sending object and the event arguments
//Returns: nothing
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("Charlie Barber\nCS 1400-X01\nProject 9");
}
//Enter Button Clicked
//Purpose: To store the info in an array when the button is pressed
//Parameters: The sending object and the event arguments
//Returns: nothing
private void button1_Click(object sender, EventArgs e)
{
//Get the information from the text box and store it in a variable
string userInput = nameTextBox.Text;
if (userInput != "")
{
//Create a new object with the parameterized constructor
// myBowlingTeam = new BowlingTeam(userInput);
//Split the string into two separte pieces of data
myBowlingTeam.SplitAndDisperseArray();
//Clear the text box
nameTextBox.Clear();
}
else
{
int highestScore = myBowlingTeam.CalcHighestScore();
}
}
//Nothing
private void nameTextBox_TextChanged(object sender, EventArgs e)
{
//Get the information from the text box and store it in a variable
string userInput = nameTextBox.Text;
//Create a new object with the parameterized constructor
myBowlingTeam = new BowlingTeam(userInput);
}
}
What is stopping you from using a class for the players inside the team? Keep the arrays synchronised in your solution seems more trouble than its worth.
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace Observable
{
class BowlingTeam
{
public string TeamName { get; set; }
private readonly IList<Player> players = new ObservableCollection<Player>();
public IList<Player> Players
{
get
{
return players;
}
}
public void AddPlayer(string name, int score)
{
AddPlayer(new Player(name, score));
}
public void AddPlayer(Player p)
{
players.Add(p);
}
public Player HighestRanked()
{
if (Players.Count == 0)
{
// no players
return null;
}
int max = 0, index = -1;
for (int i = 0; i < Players.Count; i++)
{
if (Players[i].Score > max)
{
index = i;
max = Players[i].Score;
}
}
if (index < 0)
{
// no players found with a score greater than 0
return null;
}
return Players[index];
}
public BowlingTeam()
{
}
public BowlingTeam(string teamName)
{
this.TeamName = teamName;
}
}
class Player
{
public string Name { get; set; }
public int Score { get; set; }
public Player()
{
}
public Player(string name, int score)
{
this.Name = name;
this.Score = score;
}
public override string ToString()
{
return string.Format("{0} {1:n2}", Name, Score);
}
}
}
which could be manipulated as such
BowlingTeam b1 = new BowlingTeam("SO");
b1.AddPlayer("Player 1", 100);
b1.AddPlayer("Player 2", 135);
b1.AddPlayer("Player 3", 90);
b1.AddPlayer("Player 4", 127);
Console.WriteLine("Highest ranked player: {0}", b1.HighestRanked());
An advantage for later is that you can hang on the OnCollectionChangedEvents of your players, to be notified when players were added/removed.
I have a generic type called Vector<T>, I created it as so, cause the T might be float or Complex :
public class Vector<T>
{
#region Properties
public ulong Length
{
get
{
return _length;
}
}
public VectorType VectorType
{
get
{
return _vectorType;
}
}
#endregion
#region Indexers
public T this[ulong index]
{
get
{
return _data[index];
}
set
{
_data[index] = value;
}
}
#endregion
#region Constructors
public Vector(VectorType vectorType, T[] data)
{
if (!((data is float[]) || (data is Complex[])))
{
throw new InvalidDataException("Data must be array of float or array of Complex");
}
_data = new T[_length = (ulong)data.Length];
for (ulong i = 0; i < _length; i++)
{
_data[i] = data[i];
}
_vectorType = vectorType;
}
public Vector(VectorType vectorType, Vector<T> vector)
{
_data = new T[_length = vector.Length];
for (ulong i = 0; i < _length; i++)
{
_data[i] = vector[i];
}
_vectorType = vectorType;
}
#endregion
#region Methods
//Unity Matrix, this vector has 1/N everywhere
public static Vector<float> e(VectorType vectorType, ulong length)
{
var data = new float[length];
for (ulong i = 0; i < length; i++)
{
data[i] = (float)1 / length;
}
var vectorE = new Vector<float>(vectorType, data);
return vectorE;
}
public float Sum()
{
float sum = 0;
if (_data is float[])
{
sum = (_data as float[]).Sum();
}
else
{
if (_data is Complex[])
{
for (ulong i = 0; i < _length; i++)
{
sum += (float)
Math.Sqrt(Math.Pow((_data[i] as Complex?).Value.Real, 2) +
Math.Pow((_data[i] as Complex?).Value.Imaginary, 2));
}
}
}
return sum;
}
public bool CheckIfSochasitc()
{
return Math.Abs(Sum() - 1) < float.Epsilon;
}
public void Normalize()
{
var sum = Sum();
if (_data is float[])
{
for (ulong i = 0; i < _length; i++)
{
float x = ((float) _data[i])/sum;
_data[i] = (T)x;
}
}
}
#endregion
#region Operators
//I omitted the code inhere to avoid overload
#endregion
#region Fields
private ulong _length;
private readonly VectorType _vectorType;
private T[] _data;
#endregion
}
public enum VectorType
{
Row,Column
}
My problem is that I have a generic array (if I can call it so) :
private T[] _data;
And I have the Normalize() method:
public void Normalize()
{
var sum = Sum();
if (_data is float[])
{
for (ulong i = 0; i < _length; i++)
{
//Here is the problem
_data[i] = ((_data[i] as float?) / sum);
}
}
}
This doesn't work saying can't cast float to T tried to search but couldn't find helpful aide, any clarification I'd be thankful.
Update :
The Sum() method always returns a float
It's not clear why you're converting to float? at all (or why you're using ulong as the index variable type...) but you just need to cast the result back to T - otherwise you can't assign it back into an array of type T[]. Additionally, you need to cast to object (in order to convert back to T:
float x = ((float) (object) data[i]) / sum;
data[i] = (T) (object) x;
You can use float? for the first line, with as, to avoid boxing - but then you need to get the non-nullable value:
float x = (data[i] as float?).Value / sum;
Both are pretty ugly :(
As noted in comments though, this sort of thing is usually an indication of the design not really being properly generic at all. We don't know what type Sum() returns, but you should consider just how "general" your type is to start with.
May be you can try this
if (typeof(_data) == float[])
{
for (ulong i = 0; i < _length; i++)
{
_data[i] = ((_data[i] as float?) / sum);
}
}
How can I make an array with 400 elements of type myClass and pass different args to each of them?
I have two classes: mainClass and myClass. I want to create the array in mainClass. as you can see myClass needs 3 args.
myClass:
namespace prj1
{
class myClass
{
public myClass(int A, int B int C)
{
...
...
...
}
}
}
mainClass:
namespace prj1
{
class mainClass
{
public myClass[] myVar = new myClass[400];
public mainClass(int y, int m, int d)
{
...
...
...
}
}
}
If I have to use setValue to initialize them how can I do this? How should I pass 3 args?
for (int i = 0; i < 400; i++)
{
myVar.SetValue(object Value, i);
}
Why don't you just construct each instance within the loop you already have?
for(int i = 0; i < myVar.Length; i++)
{
myVar[i] = new myClass(arg1, arg2, arg3);
}
You have an appropriate constructor already, and you're initializing within a loop... 1 + 1 == 2, let's not try and reinvent the wheel shall we?
Try this,
for (int i = 0; i < 400; i++)
{
myVar[i]=new MyClass(y,m,d);
}
//or
for (int i = 0; i < 400; i++)
{
myVar.SetValue(new MyClass(y,m,d),i);
}
for (int i = 0; i < 400; i++)
{
myClass tempObject = new myClass(y,m,d);
myVar.SetValue(tempObject,i)
}
Is there a way to have a static class have static data that does not clear itself at the end of the function call?
i.e. given:
static class Class1
{
static int[] _array;
static Class1()
{
_array = new[] {2};
}
public static void FillArray()
{
List<int> temp = new List<int>();
for(int i=0;i<100;i++)
temp.Add(i);
_array = temp.ToArray();
}
public static int[] GetArray()
{
return _array;
}
}
How can I get GetArray() to return something other than null?
EDIT: I want to call this code:
int[] array1 = Class1.GetArray();
for (int i = 0; i < array1.Length;i++ )
Console.WriteLine(array1[i]);
Class1.FillArray();
for (int i = 0; i < array1.Length; i++)
Console.WriteLine(array1[i]);
and not get two 2s. How can I make that happen?
int[] array1 = Class1.GetArray();
for (int i = 0; i < array1.Length;i++ )
Console.WriteLine(array1[i]);
Class1.FillArray();
for (int i = 0; i < array1.Length; i++)
Console.WriteLine(array1[i]);
In this code, you are getting the memory address of the first int[] {2} array and storing that as array1. Then when you call FillArray() you are creating the new List of arrays, and only setting its memory back to the _array in the class, not array1. That is not a reference to the memory in the class, but to the actual original array. So then, when you loop back through, you are still looking at the same memory block.
You should probably be doing this instead:
int[] array1 = Class1.GetArray();
for (int i = 0; i < array1.Length;i++ )
Console.WriteLine(array1[i]);
Class1.FillArray();
array1 = Class1.GetArray();
for (int i = 0; i < array1.Length; i++)
Console.WriteLine(array1[i]);
Update
if you change your Class1 to look like this, you will see that you are changing the data in the class.
static class Class1
{
static int[] _array;
static Class1()
{
_array = new[] { 2 };
}
public static void FillArray()
{
List<int> temp = new List<int>();
for (int i = 0; i < 100; i++)
{
temp.Add(i);
}
_array = temp.ToArray();
PrintArray();
}
public static int[] GetArray()
{
PrintArray();
return _array;
}
private static void PrintArray()
{
foreach (int i in _array)
{
System.Console.Write(String.Format("{0},", i));
}
}
}
Because it will print out the elements in the array after each call.
use a static constructor...
static class Class1
{
private static readonly int[] _array;
static Class1()
{
List<int> temp = new List<int>();
for(int i=0;i<100;i++)
temp.Add(i);
_array = temp.ToArray();
}
public static int[] GetArray()
{
return _array;
}
}
you can write something like
private static readonly int[] array = FillArray();