The name 'myNumber' does not exist in the current context" - c#

I'm sure this has a very simple solution but I'm new to C# and I just can't seem to get rid of this error message.
I'm trying to generate a random number between 1 and 100 inclusive in my code.
namespace FirstName_A1
{
class FromTwoDtoOneD
{
static void Main1()
{
int[,] twoDArray = new int[10,12];
int[] oneDArray = new int[10*12];
FillTwoDimArray(twoDArray);
DisplayTwoDimArray(twoDArray);
StoreValues(twoDArray, oneDArray);
DisplayOneDimArray(oneDArray);
}
static void FillTwoDimArray(int[,] twoDArray) //method to fill twoD array with random numbers
{
Random myRandom = new Random(); //Random class is under System namespace
myNumber = myRandom.Next(1, 101); //generates number between 1-100 inclusive
for(int a=0;a<10;a++)
{
for(int b=0;b<12;b++)
{
twoDArray[a, b] = myNumber;
}
}
}
static void DisplayTwoDimArray(int[,] twoDArray)
{
Console.WriteLine("Two-Dimensional Array");
for(int a=0;a<10;a++)
{
for(int b=0;b<12;b++)
{
Console.Write(twoDArray[a, b] + " ");
}
Console.WriteLine();
}
}
static void StoreValues(int[,] twoDArray, int[ ] oneDArray)
{
int c = 0;
for(int a=0;a<10;a++)
{
for(int b=0;b<12;b++)
{
oneDArray[c] = twoDArray[a, b];
c = c + 1;
}
}
}
static void DisplayOneDimArray(int[] oneDArray)
{
Console.WriteLine("One Dimensional Array");
for(int a=0;a<10;a++)
{
Console.WriteLine(oneDArray[a]);
}
}
}
}

You haven't declared the variable myNumber in the FillTwoDimArray method. I'm declaring with var myNumber = myRandom.Next(...);
static void FillTwoDimArray(int[,] twoDArray) //method to fill twoD array with random numbers
{
Random myRandom = new Random(); //Random class is under System namespace
var myNumber = myRandom.Next(1, 101); //generates number between 1-100 inclusive
for(int a=0;a<10;a++)
{
for(int b=0;b<12;b++)
{
twoDArray[a, b] = myNumber;
}
}
}

Related

How to store instances of an integer in an array in a separate variable in C#?

Goal
A C# program that picks a random number from 1 to 6 and stores it
Question
Which way to store: the entire sequence or an array of 6 elements with increments to the n-1 index for every hit of n?
Code
using System;
namespace DiceProbabilityCalc
{
class Program
{
static void Main(string[] args)
{
Random rnd = new Random();
int[] instanceCount = new int[1000];
for (int i = 0; i < 999; i++)
{
int num = rnd.Next(1, 7);
}
}
}
}
Thanks to #PeterSmith and #Martheen for solving the question in the comments: The array instanceCount can be used to store the number of instances instead of the entire sequence. This is the resulting code.
using System;
namespace DiceProbabilityCalc
{
class Program
{
static void Main(string[] args)
{
Random rnd = new Random();
int[] instanceCount = new int[6];
for (int i = 0; i < 999; i++)
{
int num = rnd.Next(1, 7);
instanceCount[num - 1]++;
}
for (int j = 0; j < instanceCount.Length; j++)
{
Console.WriteLine(instanceCount[j]);
}
}
}
}

C#: How to assign random int values to variables?

I have made a dice class that includes a method which uses random.next to determine a random int value from 1-6.
Fairdice.cs:
class FairDice
{
//defining variable and property
private Random rnd;
public int Current { get; private set; }
public FairDice()
{
rnd = new Random(Guid.NewGuid().GetHashCode());
Current = 0;
}
public int FRoll()
{
Current = rnd.Next(1, 7);
return Current;
}
RollDice.cs that features a loop for printing.
static class RollDice
{
public static void Roll(this int count, Action action)
{
for (int i = 0; i < count; i++)
{
action();
}
}
}
Program.cs includes this code, which prints out 5 random values between 1-6:
FairDice fd = new FairDice();
5.Roll(() => Console.WriteLine("Dice: " + fd.FRoll()));
Problem: I wish to assign the random values in each variable and store and save them in either a list or array for future use.
clarification:
lets say it prints out the numbers: 1, 2, 3, 4, 5 - i then wish to assign each value a variable: a = 1, b = 2, ... f = 5.
and/or simply store the values in an array {1, 2, 3, 4, 5}
Is there any way to do this?
If you want to store the values returned by calling FRoll then you could do something like this:
FairDice fd = new FairDice();
var numbers = new List<int>();
5.Roll(() => numbers.Add(fd.FRoll())); // Append the values to the list as we generate them
var firstNumberRolled = numbers[0]; // Access the values later
Console.WriteLine($"The first number rolled was {firstNumberRolled}");
Once the throw results are into an array you can extract assign variables as necessary.
class FairDice
{
private static int _seed;
private static ThreadLocal<Random> threadLocal = new ThreadLocal<Random>
(() => new Random(Interlocked.Increment(ref _seed)));
static FairDice()
{
_seed = Environment.TickCount;
}
private static Random Rng { get { return threadLocal.Value; } }
public int Roll()
{
return Rng.Next(1, 6);
}
}
static class RollDice
{
public static int[] Roll(this int count, FairDice dice)
{
int[] values = new int[count];
for (int i = 0; i < count; i++)
{
values[i] = dice.Roll();
}
return values;
}
}
class Program
{
static void Main(string[] args)
{
FairDice fd = new FairDice();
int[] values = 5.Roll(fd);
Console.WriteLine(String.Join(",", values.Select(x => x.ToString()).ToArray()));
}
}
add this to FairDice (lines with '*'):
class FairDice
* private int[] returnedValues;
public int FRoll()
{
Current = rnd.Next(1, 7);
* returnedValues[Current]++;
return Current;
}
*public void GetreturnedValues()
* {
* for (int i = 1; i < 7; i++)
* {
* Console.WriteLine("{0}: {1}", i, returnedValues[i]);
* }
* }
After this adding d.GetreturnedValues(); to you Program.cs will show how many time the different values where thrown.

Making a simple AI for a battleship program in C#

I've just recently started learning to code C# to hopefully get a job someday. I'm trying to get 3 randomly generated points in a 5x5 grid. For some reason when I try to run it it just auto crashes. For testing purposes I added a Console.WriteLine and Console.ReadKey to try and see the output but it still auto closed immediately. Is there any reason why this shouldn't be working? Thanks for any help :D
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp4
{
class Program
{
static void Main(string[] args)
{
}
public void CompB()
{
int[] AiB = new int[6];
for (int i = 1; i < 3; i++)
{
Random rnd = new Random();
int AiR = rnd.Next(0, 26);
AiB[i] = AiR;
}
Console.WriteLine(AiB[0]);
Console.ReadKey();
}
}
}
your method is not called. that is why it auto closes.
nothing is done in your program.
class Program
{
static void Main(string[] args)
{
int[] AiB = new int[6];
for (int i = 1; i < 3; i++)
{
Random rnd = new Random();
int AiR = rnd.Next(0, 26);
AiB[i] = AiR;
}
Console.WriteLine(AiB[0]);
Console.ReadKey();
}
}
now the output is:
complete code:
class Program
{
static void Main(string[] args)
{
CompB();
}
public static void CompB()
{
int[] AiB = new int[6];
for (int i = 1; i < 3; i++)
{
Random rnd = new Random();
int AiR = rnd.Next(0, 26);
AiB[i] = AiR;
}
Console.WriteLine(AiB[0]);
Console.ReadKey();
}
}
This is how i found out that the method was not used:
Before:
After:
As already called out above you are missing the CompB();from the main method .
One more I just looked into the for loop in line 18 it starts from in the i=1 but you are doing
System.Console.WriteLine(AiB[0]);
you should try out something like
System.Console.WriteLine(AiB[1]);
static void Main(string[] args)
{`enter code here`
CompB();
}
public static void CompB()
{
int[] AiB = new int[6];
for (int i = 1; i < 3; i++)
{
Random rnd = new Random();
int AiR = rnd.Next(0, 26);
AiB[i] = AiR;
}
System.Console.WriteLine(AiB[1]);
System.Console.ReadKey();
}
You need to call your method CompB() from the main method. Then you have to write out all the values int the array.
class Program
{
static void Main(string[] args)
{
CompB();
}
public static void CompB()
{
int[] AiB = new int[6];
for (int i = 1; i < 3; i++)
{
Random rnd = new Random();
int AiR = rnd.Next(0, 26);
AiB[i] = AiR;
}
//Write all values:
for (int i = 0; i < 6; i++)
{
System.Console.WriteLine("Value of {0}: {1}", i, AiB[i]);
}
System.Console.ReadKey();
}
}

Code does not recognize Listbox when I tried to fill it with array

Hi I am trying to fill a simple ListBox with array. The code that I have; it throws this error
Error 1 The name 'myArrayList' does not exist in the current context
public class Class1
{
public void FillArray()
{
int min = 1;
int max = 1000;
int[] testArray = new int[1000];
Random randNumber = new Random();
for (int i = 1; i < testArray.Length; i++)
{
testArray[i] = randNumber.Next(min, max);
}
foreach (int value in testArray)
{
myArrayList.ItemSource = testArray;
}
}
}

Generating random numbers from giving numbers in c#

User enters numbers to 10 textbox and i sent them to an array. Now i want to generate random numbers from this array. What can i do?
Something like this:
public class Randomizer<T>
{
private readonly Random _random = new Random();
private readonly IList<T> _numbers;
public Randomizer(IList<T> numbers)
{
_numbers = numbers;
}
public T Next()
{
int idx = _random.Next(0, _numbers.Count);
return _numbers[idx];
}
}
Usage:
var r = new Randomizer<int>(new int[] { 10, 20, 30, 40, 50 });
for (int i = 0; i < 100; i++)
Console.Write(r.Next() + " ");
Or do you want to shuffle the array?
[Edit]
To shuffle the array, you can use the Fisher–Yates shuffle shown in this post:
// https://stackoverflow.com/questions/108819/110570#110570
public class Shuffler
{
private Random rnd = new Random();
public void Shuffle<T>(IList<T> array)
{
int n = array.Count;
while (n > 1)
{
int k = rnd.Next(n);
n--;
T temp = array[n];
array[n] = array[k];
array[k] = temp;
}
}
}
If you want the interface to be same as the Randomizer class above, you can modify it to use the Shuffler class:
public class Randomizer<T>
{
private readonly Shuffler _shuffler = new Shuffler();
private readonly IList<T> _numbers;
public Randomizer(IList<T> numbers)
{
_numbers = new List<T>(numbers);
_shuffler.Shuffle(_numbers);
}
volatile int idx = 0;
public T Next()
{
if (idx >= _numbers.Count)
{
_shuffler.Shuffle(_numbers);
idx = 0;
}
return _numbers[idx++];
}
}
Note that the code is not thread safe, so some locking should be implemented if Next method might be called simultaneously from multiple threads.
Seed the standard System.Random class with a value from the array? If you need your random numbers to depend on ALL array items, then just XOR them all.
public static Random BuildSeededRandom(int[] data)
{
if ( data == null || data.Length < 1 )
return new Random();
int xor = 0;
foreach ( var i in data )
xor ^= i;
return new Random(xor);
}

Categories

Resources