Hi I'm struggling with this assignment.
When the program starts 4 methods are being executed where the next thing hapens.
One array gets filled with 100 random numbers between 1 and 1000 000 (method1)
The first listbox gets filled with aal the numbers from the array (method2)
The second listbox gets filled with the 5 smalest numbers from the array (method3)
The third listbox gets filled with the 5 biggest numbers from the array (method3)
This has to run when the program starts.
So far my array gets filled and the first listbox gets filled to.
But only in one and not through different methods. I tried to split it up but without success. And my deadline is near.
Sorry for the rookie mistakes btw.
public partial class RandomArray : Form
{
// array met onze 100 waarden
int[] arrRandomNumbers = new int[100];
// random variabele
Random randomGenerator = new Random();
int iRandomNumber = 0;
public RandomArray()
{
InitializeComponent();
AddNumbers();
}
private void AddNumbers()
{
for (int i = 0; i < arrRandomNumbers.Length; i++)
{
iRandomNumber = randomGenerator.Next(1, 1000000);
arrRandomNumbers[i] = iRandomNumber;
}
foreach (var number in arrRandomNumbers)
{
lbxOne.Items.Add(number);
}
}
}
If I understand, you're trying to populate each list in a different function. This is untested but something like this should work:
using System.Linq; //Make sure to add Linq access
public partial class RandomArray : Form
{
// array met onze 100 waarden
int[] arrRandomNumbers = new int[100];
// random variabele
Random randomGenerator = new Random();
int iRandomNumber = 0;
public RandomArray()
{
Console.WriteLine("Creating new RandomArray Class.");
AddNumbers();
PopulateListOne();
PopulateListTwo();
PopulateListThree();
}
private void AddNumbers()
{
for (int i = 0; i < arrRandomNumbers.Length; i++)
{
iRandomNumber = randomGenerator.Next(1, 1000000);
arrRandomNumbers[i] = iRandomNumber;
}
}
private void PopulateListOne() {
Console.WriteLine("All Numbers:");
foreach (var number in arrRandomNumbers)
{
Console.WriteLine(number.ToString());
//lbxOne.Items.Add(number);
}
}
private void PopulateListTwo() {
Console.WriteLine("Top 5 Numbers:");
var top5 = arrRandomNumbers.OrderByDescending(x => x).Take(5).ToArray();
foreach (var number in top5)
{
Console.WriteLine(number.ToString());
//lbxTwo.Items.Add(number);
}
}
private void PopulateListThree() {
Console.WriteLine("Bottom 5 Numbers:");
var bot5 = arrRandomNumbers.OrderBy(x => x).Take(5).ToArray();
foreach (var number in bot5)
{
Console.WriteLine(number.ToString());
//lbxThree.Items.Add(number);
}
}
}
In a fiddle: https://dotnetfiddle.net/h3v6n0
I think you want this:
I suggest the following:
create a data model to hold the data (the number lists).
public class RandomNumberLists
{
static readonly Random rng = new Random();
public RandomNumberLists(int count)
{
Numbers = new int[count];
for (int i = 0; i < Numbers.Length; i++)
{
Numbers[i] = rng.Next(1, 1000000);
}
MinFive = Numbers.OrderBy((x) => x).Take(5).ToArray();
MaxFive = Numbers.OrderByDescending((x) => x).Take(5).ToArray();
}
public int[] Numbers { get; }
public int[] MinFive { get; }
public int[] MaxFive { get; }
}
Use the built-in methods of .OrderBy() and OrderByDescending() to sort the list of random numbers from bottom to top and top to bottom. Then extract the first n-th numbers with the .Take(n) method and finally make a copy with the .ToArray().
Use the listbox .DataSource property to set the items in the listbox for display
public partial class Form1 : Form
{
RandomNumberLists numberLists;
public Form1()
{
InitializeComponent();
numberLists = new RandomNumberLists(100);
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
listBox1.DataSource = numberLists.Numbers;
listBox2.DataSource = numberLists.MinFive;
listBox3.DataSource = numberLists.MaxFive;
}
}
Here I initialize the numbers in the form constructor, and assign the lists to the listboxes in the .OnLoad() method which happens before initial display of the form.
Related
class Asient
{
private List<String> letras = new List<String> {
"A","B","C","D","E","F","G","H","J"};
private List<string> fila = new List<string> {
"1","2","3","4","5","6","7","8"};
private List<string> asientos= new List<string>();
public Asient(){
for (int i = 0; i < letras.Count; i++){
for (int n = 0; n < letras.Count; n++){
string sillaletra = letras[i] + fila[n];
asientos.Add(sillaletra);
}
}
}
public List<string> GetAsientos(){
return this.asientos;
}
}
class Mainn
{
static void Main(string[] args)
{
Asient sillas = new Asient();
sillas.GetAsientos();
}
}
And the code give me this runtime error:
Unhandled exception. System.ArgumentOutOfRangeException: Index was out of range.
Must be non-negative and less than the size of the collection. (Parameter 'index')
at System.Collections.Generic.List`1.get_Item(Int32 index)
at A05CINE.Asient..ctor() in D:\Users\x\x\x\x\x\c#\x\x\x.cs:line 15
at A05CINE.Mainn.Main(String[] args) in D:\Users\x\Desktop\x\x\x\c#\A05\x\x.cs:line 31
Does someone know how to fix that?
I tried using
asientos.Add(letras[i] + fila[n]);
string sillaletra = letras[i] + fila[n];
asientos.Add(sillaletra);
It seems, you are looking for Cartesian Join, i.e. you want List<string> to be
{ "A1", "A2", ..., "A8", "B1", ..., "B8", ..., "J8" }
If it's your case, you can put a simple Linq query for this:
using System.Linq;
...
public Asient() {
asientos = letras
.SelectMany(letter => fila.Select(digit => letter + digit))
.ToList();
}
You have more letters than numbers, add
private List<string> fila= new List<string>{"1","2","3","4","5","6","7","8","9"};
and it will work.
You are looping through the same length. Into your loop, both ends at position letras.Count, but list has not the same length.
Your loop should iterate over the length of each array like this:
for (int i = 0; i < letras.Count; i++)
{
for (int n = 0; n < fila.Count; n++)
{
//...
}
}
Note that the first array goes from 0 to letras.Count.
And second goes from 0 to fila.Count.
Now, each position is iterated.
I am trying to learn C# and doing some questions i googeld. This is the task to do:
*"Beginner level:
The task is to make
a dice game where the user throws 3
Each 12-sided dice (numbers
shall be randomly selected and stored in an array / field or list).
Add up the total of the dice and show on the screen.
Create a function / method that accepts a figure
(the total sum of the dice). Function / method
should return the text "Good throw" if the figure
is higher or equal to 20.
In all other cases, the text
"Sorry" is returned.
Call the function / method in the main method
and prints the total and the text.
Advanced level:
This is an extension of the task where you must use a class to simulate a dice. The user shall have the option of writing a x y-sided dice himself.
If the total sum of a roll of the dice generates a score that is> 50% of the maximum score, the words "good throw" is displayed.
This logic can be in your main method.
Create the class described in the class diagram and use appropriate
way in your code."*
The thing is that i cant get it to work, the array in my class do not save my numbers im typing in... I only get the reslut 0. I think i have just done some big misstake i cant see...
This is the Main code:
static void Main(string[] args)
{
List<Dice> _Dice = new List<Dice>();
int a = 0;
int times = int.Parse(Interaction.InputBox("Write how many times you want to repeat the game:"));
while (a != times)
{
int antThrow = int.Parse(Interaction.InputBox("Write how many times you want each dice to get thrown:"));
int xChoice = int.Parse(Interaction.InputBox("Write how many dice you want to throw:"));
int yChoice = int.Parse(Interaction.InputBox("Write how many sides you want each dice should have:"));
_Dice.Add(new Dice(xChoice,yChoice, antThrow));
a++;
}
int e = 1;
foreach (var item in _Dice)
{
Interaction.MsgBox(string.Format("Result of game {0}: {1}", e++, item.Tostring()));
}
}
This is the Dice class:
class Dice
{
static int _xChoice, _yChoice, _throw;
static List<int> sum = new List<int>();
static int w = 0;
static int _sum;
static int[,] dice = new int[_xChoice, _yChoice];
public string Tostring()
{
int half = _sum / 2;
if (half <= _sum/2)
{
return "Good throw!" + _sum;
}
else
{
return "Bad throw!";
}
}
void random()
{
Random rnd = new Random();
while (w != _throw)
{
for (int i = 0; i < dice.GetLength(0); i++)
{
for (int j = 0; j < dice.GetLength(1); j++)
{
dice[i, j] = rnd.Next(1, _yChoice);
_sum += dice[j, i];
sum.Add(_sum);
}
}
w++;
}
}
public Tarning(int Xchoice, int Ychoice, int throw)
{
_throw = thorw;
_xChoice = Xchoice;
_yChoice = Ychoice;
}
}
Your main problem is in the static keyword. Static field means that there's only
one field for all the instances, which is not your case: you need each instance of Dice has its own fields' values.
class Dice {
// no static here
private int _xChoice, _yChoice, _throw;
// no static here
private List<int> sum = new List<int>();
// no static here
private int w = 0;
// no static here
private int _sum;
// no static here
private int[,] dice = new int[_xChoice, _yChoice];
// BUT, you want a random generator for all the instances, that's why "static"
private static Random rnd = new Random();
// When overriding method mark it with "override"
// And Be Careful with CAPitalization:
// the method's name "ToString" not Tostring
public override string ToString() {
...
}
void random() {
// Do not create Random generator each time you call it:
// It makes the random sequences skewed badly!
// Istead use one generator for all the calls, see the code above
// private static Random rnd = new Random();
// Random rnd = new Random();
...
}
...
class Program
{
static void Main(string[] args)
{
var dice = new List<DiceLogic>();
int a = 0;
int times = GetTimes();
while (a != times)
{
int antThrow = GetAntThrow();
int xChoice = GetXChoice();
int yChoice = GetYChoice();
dice.Add(new DiceLogic(xChoice, yChoice, antThrow));
a++;
}
int e = 1;
foreach (var item in dice)
{
Console.WriteLine("Result of game {0}: {1}", e++, item.Tostring());
}
Console.ReadLine();
}
private static int GetTimes()
{
while (true)
{
Console.WriteLine("Write how many times you want to repeat the game:");
int times;
var result = int.TryParse(Console.ReadLine(), out times);
if (result) return times;
Console.WriteLine("Value must be a number.");
}
}
private static int GetAntThrow()
{
while (true)
{
Console.WriteLine("Write how many times you want each dice to get thrown:");
int antThrow;
var result = int.TryParse(Console.ReadLine(), out antThrow);
if (result) return antThrow;
Console.WriteLine("Value must be a number.");
}
}
private static int GetXChoice()
{
while (true)
{
Console.WriteLine("Write how many dice you want to throw:");
int getXChoice;
var result = int.TryParse(Console.ReadLine(), out getXChoice);
if (result) return getXChoice;
Console.WriteLine("Value must be a number.");
}
}
private static int GetYChoice()
{
while (true)
{
Console.WriteLine("Write how many sides you want each dice should have:");
int getXChoice;
var result = int.TryParse(Console.ReadLine(), out getXChoice);
if (result) return getXChoice;
Console.WriteLine("Value must be a number.");
}
}
}
public class DiceLogic
{
public string Tostring()
{
int maxScore = _diceSides*_dices;
if (_result >= maxScore / 2)
{
return "Good throw! " + _result;
}
return "Bad throw! " + _result;
}
private readonly int _dices;
private readonly int _diceSides;
private readonly int _throwDice;
private int _result;
private void CalculateResult()
{
var rnd = new Random();
for (int i = 0; i < _dices; i++)
{
int currentResult = 0;
for (int j = 0; j < _throwDice; j++)
{
currentResult = rnd.Next(0, _diceSides);
}
_result += currentResult;
}
}
public DiceLogic(int dices, int diceSides, int throwEachDice)
{
_dices = dices;
_diceSides = diceSides;
_throwDice = throwEachDice;
CalculateResult();
}
}
This is an example of how you could implement what they are asking, go through te code line by line with the debugger so you understand what is going on.
You never call the method random(). Therefore, the value of your member variable _sum is never changed and remains 0. You need to call the method random() somewhere. You should probably make it public and call it from your main method after you have set up all your dice.
Furthermore, your member variables in the Dice class are all static! That means that the different Dice instances will all share the same values. I think this is not intended. You should make the variables instance variables by removing the static modifier.
Your method Tarning is not called and it takes a reserved word “throw” [I believe it was supposed to be thorw]. The method is not void so it must return a type.
Random() is not invoked and does display anything.
Dice has not constructor that has 3 arguments within its braces but it’s declared as _Dice.Add(new Dice(xChoice,yChoice, antThrow));
I'm working on a small programme for booking seats on an airplane - And I keep getting this error. i want the programme to show me which seats on the plane (flysaeder) are being booking by what passenger (passagerer). Only, If I enter in more seats than I have passengers, it won't run - I need it to allow open seats (less "passagerer" than "flysaeder"). What am I doing wrong?
I'm kinda new at this, so I apologize for poor explanation.
Error occurs on "listeOverPassagerer[index] = listeOverPassagerer[i];".
namespace eksamenvingerne
{
public partial class Form1 : Form
{
int flysaeder;
int passagerer;
Random tilfældighed = new Random();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();
listBox2.Items.Clear();
{
int.TryParse(txtsaeder.Text, out flysaeder);
int.TryParse(txtantalpassagere.Text, out passagerer);
if (passagerer > flysaeder)
{
MessageBox.Show("Ingen frie pladser!");
}
else
{
int[] listeOverPassagerer = Enumerable.Range(0, passagerer).ToArray();
int[] flypladser = new int[flysaeder];
for (int i = 0; i < flysaeder; i++)
{
int index = tilfældighed.Next(0, passagerer);
flypladser[i] = tilfældighed.Next(i, passagerer);
flypladser[i] = listeOverPassagerer[index];
listeOverPassagerer[index] = listeOverPassagerer[i];
}
for (int i = 0; i < flypladser.Length; i++)
{
listBox1.Items.Add("Sæde #" + i + ": Passagernr.:" + flypladser[i]); //listboxen udskriver indholdet af hver eneste plads.
}
}
}
}
}
}
Your logic actually is causing this problem:
First you make sure that passagerer <= flysaeder
if (passagerer > flysaeder)
{
MessageBox.Show("Ingen frie pladser!");
}
Then you do a for loop from 0 to flysaeder -1
for (int i = 0; i < flysaeder; i++)
But flysaeder might be larger than passagerer hence your access of listeOverPassagerer[i] will throw an exception since listeOverPassagerer is of length passagerer
I'm trying to create a booking service and I've been stuck on this part for many hours and I just can't figure out what I'm doing wrong.
So I've got a Two Dimensional array and when trying to print out some stuff when testing and trying to figure out what's wrong, all I get is System.String[] which doesn't really make me any wiser. I want to be able to access the details in i.e. m_nameMatrix[0,0] to check whether the seat is reserved or not.
Here's a snippet from my form code:
private void UpdateGUI(string customerName, double price)
{
string selectedItem = cmdDisplayOptions.Items[cmdDisplayOptions.SelectedIndex].ToString();
rbtnReserve.Checked = true;
lstSeats.Items.Clear();
lstSeats.Items.AddRange(m_seatMngr.GetSeatInfoStrings(selectedItem));
}
And here are two methods from my 2nd class:
public string[] GetSeatInfoStrings(string selectedItem)
{
int count = GetNumOfSeats(selectedItem);
if (count <= 0)
{
return new string[0];
}
string[] strSeatInfoStrings = new string[count];
for (int index = 0; index <= count; index++)
{
strSeatInfoStrings[index] = GetSeatInfoAt(index);
}
return strSeatInfoStrings;
}
public string GetSeatInfoAt(int index)
{
int row = (int)Math.Floor((double)(index / m_totNumOfCols));
int col = index % m_totNumOfCols;
string seatInfo = m_nameMatrix.GetValue(row, col).ToString();
return seatInfo;
}
I'm not actually getting an exception so it might be my logical thinking that's been taking a hit due to hours and hours of trying to figure it out.
EDIT:
public void ReserveSeat(string name, double price, int index)
{
int row = (int)Math.Floor((double)(index / m_totNumOfCols));
int col = index % m_totNumOfCols;
string reserved = string.Format("{0,3} {1,3} {2, 8} {3, 8} {4,22:f2}",
row + 1, col + 1, "Reserved", name, price);
m_nameMatrix[row, col] = reserved;
}
This line:
for (int index = 0; index <= count; index++)
should be:
for (int index = 0; index < count; index++)
Why? Lets say I have an array with 2 objects in it. count would be 2. However, the indexes are 0 and 1. So you have to use a less than operator.
If you're getting "System.String[]" in your messagebox, it's because you're trying to print a string[] directly, rather than the various strings it contains:
string[] data = GetSeatInfoStrings("foo");
MessageBox.Show(data);
Instead, you need to show the contents of data:
string[] data = GetSeatInfoStrings("foo");
MessageBox.Show(string.Join("\n", data));
See here for the documentation.
Suppose you had a method called ReturnArray():
class Class2
{
public string[] ReturnArray()
{
string[] str = new string[] { "hello", "hi" };
return str;
}
}
If you called ReturnArray in your main class like this:
Class2 class2 = new Class2();
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(class2.ReturnArray());
}
it will return System.String[] because MessageBox.Show(...) takes a string as an argument, in this case.
So you'll also get the same result by using MessageBox.Show(class2.ReturnArray().ToString());
Instead, you may want to do something like this:
Class2 class2 = new Class2();
private void button1_Click(object sender, EventArgs e)
{
string[] strArray = class2.ReturnArray();
listBox1.Items.AddRange(strArray);
}
i M declaring an int type array and trying to print all its elements but it prints only last element .....give me the right code.....
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
int[] arr;
int range;
public Form1()
{
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
range = Convert.ToInt32(textBox1.Text);
arr = new int[range];
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
for (int i = 0; i < range; i++)
{
arr[i] = Convert.ToInt32(textBox2.Text);
}
}
private void button1_Click(object sender, EventArgs e)
{
for(int i =0;i<range;i++)
{
textBox3.Text = textBox3.Text + arr[i].ToString();
}
}
}
}
This line: arr[i] = Convert.ToInt32(textBox2.Text); will set every element in the array to the value in textbox2. Is that your intent?
Int arrays are common. They store many integer values. And these values can be used in many ways. This introductory material covers int arrays, showing declarations, assignments, elements, loops and methods.please see here
this code is simple example that work array int
using System;
class Program
{
static void Main()
{
int[] arr1 = new int[] { 3, 4, 5 }; // Declare int array
int[] arr2 = { 3, 4, 5 }; // Another
var arr3 = new int[] { 3, 4, 5 }; // Another
int[] arr4 = new int[3]; // Declare int array of zeros
arr4[0] = 3;
arr4[1] = 4;
arr4[2] = 5;
if (arr1[0] == arr2[0] &&
arr1[0] == arr3[0] &&
arr1[0] == arr4[0])
{
Console.WriteLine("First elements are the same");
}
}
}
using System;
class Program
{
static void Main()
{
// Loop over array of integers.
foreach (int id in GetEmployeeIds())
{
Console.WriteLine(id);
}
// Loop over array of integers.
int[] employees = GetEmployeeIds();
for (int i = 0; i < employees.Length; i++)
{
Console.WriteLine(employees[i]);
}
}
/// <summary>
/// Returns an array of integers.
/// </summary>
static int[] GetEmployeeIds()
{
int[] employees = new int[5];
employees[0] = 1;
employees[1] = 3;
employees[2] = 5;
employees[3] = 7;
employees[4] = 8;
return employees;
}
}
Output
1
3
5
7
8
1
3
5
7
8
Is textBox2.Text one number, or a sequence of numbers? If it is, for example, 1,2,3 then you'll have to Split the string on , and then convert each entry of the String[] you get back to an integer, and store those in the array.
I am not sure what you are trying to do.
It appears that you are reading an input from a textbox whenever it is changed
and recreating the array to the size indicated in that textbox.
The second textbox fills the array whenever it is changed to whatever the second
textbox accepts as input (this makes no sense at all).
button1 displays array as a string, which is probably alright.
You might want to change the 2nd textbox into a button which fills the array.
Otherwise, rethink your intent of 2nd textbox, it makes no sense.
Where do you clear textBox3.Text ?
You are accumulating in this text box. When you do that, and the input overflows, you will only see the last thing added. Perhaps this is the problem. I might tweak:
private void button1_Click(object sender, EventArgs e)
{
textBox3.Text = "";
for(int i =0;i<range;i++)
{
textBox3.Text = textBox3.Text + arr[i].ToString();
}
}