This question already has answers here:
How to let the user enter any amount of variable from Console
(3 answers)
Closed 7 years ago.
I am trying to learn C# on my own. I wanted to make a dice game that lets the user enter any number of dice that he or she wants. So if the user enters 10 dice, 10 list of the dice roll would appear next to each other. Here is where I can't figure it out. How can I let the user input any number of dice he or she wants? It would be impractical to use an array or list because I have to give each section of the 10 times or more. It would be nice to give a simple example.
static void Main(string[] args)
{
Random numbergen = new Random();
int dice1=0;
int dice2=1;
for (int counter = 0; counter <= 1; counter++)
{
while (dice1 != dice2)
{
dice1 = numbergen.Next(1, 7);
dice2 = numbergen.Next(1, 7);
if (dice1 == dice2)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine(dice1 + "\t" + dice2);
counter++;
dice1 = 0;
dice2 = 1;
}
else if (dice1 != dice2)
{
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine(dice1 + "\t" + dice2);
}
if (counter ==1 )
{
break;
}
}
}
Console.ReadLine();
}
Most likely, you want a List<>, something like this:
int size = 10; // Or user input
List<int> dice = new List<int>(size);
The form of the constructor that takes an Int32 argument pre-allocates that many items in the list.
Then, rather than dice1 = numbergen.Next(1, 7);, you have dice[0] = ....
You'll obviously need a loop to generate the values and decide how you want to interpret your condition of two of them being equal (which will probably also require a loop of some sort), but if I'm understanding the question correctly, this should get you going.
(You can do something similar with an array, but lists are handy in other ways, as you can see from the first link.)
Alternatively, instead of pre-allocating and filling them in separately, you can allocate an empty list and then fill your items in with something more like:
int size = 10;
for (int i = 0; i < size; i++) {
dice.Add(numbergen.Next(1, 7));
}
That's probably preferred by most people, but the difference should be pretty much negligible for this sort of work.
(And while you're at it, change your for loop to a while and change counter to a bool with a more useful name...)
Related
so I'm new to coding and I've decided to learn C# with the whole Covid-19 going on, and I've run into a small problem if anybody can assist me.
I'm just writing a basic C# program to allow the user to input 5 numbers into an array and then display the array, but for some reason, I only display the number 5, not the whole array.
Please find my code: ( if anyone can make it easier for me please help me lol (: )
int[] numbers = new int[5];
int num = 0;
int i = 0;
Console.WriteLine("This porgram allows the user to input 5 numbers into an array");
Console.Write("--------------------------------------------------------------");
Console.WriteLine("\n");
for ( i = 0; i < numbers.Length; i ++)
{
Console.WriteLine("Please input number");
num = Convert.ToInt32(Console.ReadLine());
}
for (i = 0; i < numbers.Length; i++)
{
Console.ReadLine();
Console.WriteLine("Your array is: " , numbers );
}
Console.WriteLine();
// any help will be appreciated!
Two problems:
1) You haven't put the number coming in. After
num = Convert.ToInt32(Console.ReadLine());
put
numbers[i] = num;
Though in fact num is superfluous, so you could just have
numbers[i]= Convert.ToInt32(Console.ReadLine());
2) In the second loop you need to display the specific array element:
Console.WriteLine("Your array item is: " , numbers[i] );
Also, not sure what the ReadLine() in the second loop is for - just means the users has to hit return to see each number.
It's worth mentioning a few other issues in the code:
Variables should be declared as close as possible to where they are used. this i should be declared separately for each for loop - for(int i = 0; ... and num should be declared inside the loop (though as mentioned, it's redundant).
Be clear on the difference between Console.Write() and Console.WriteLine(). WriteLine() simply adds a \n to whatever is displayed. Thus it would be clearer (for the same output to have:
Console.WriteLine("--------------------------------------------------------------");
Console.WriteLine();
here is code:
it is the basic syntax of displaying an array.
public class Work
{
public static void Main()
{
int[] arr = new int[5];
int i;
Console.Write("\nRead & Print elements of an array:\n");
Console.Write("-----------------------------------------\n");
Console.Write("Input 5 elements in the array :\n");
for(i=0; i<5; i++)
{
Console.Write("element - {0} : ",i);
arr[i] = Convert.ToInt32(Console.ReadLine());
}
Console.Write("\nElements in array are: ");
for(i=0; i<5; i++)
{
Console.Write("{0} ", arr[i]);
}
Console.Write("\n");
}
}
I suppose to fill the value each time the user try to make an appointment. There is Two type of Appointment: Appointment a and Appointment b. Each appointment can make it only 4 a day. So, my dimensional would have two columns for types of appointment and 4 rows for 4 appointments. I just tried if the user types only "a".
If the user types "a" for the first time, my 2D array will look like:
1111
1000
If the user types "a" for the second time, the 2D array will look like:
1111
1200
And so on... So finally the 2D array will look like:
1111
1234
int[,] slots = new int[4,2];
string appt_type;
string choice = "Y";
while (choice == "Y")
{
Console.WriteLine("Please enter a or b");
appt_type = Console.ReadLine();
if (appt_type == "a")
{
for (int i=0; i<slots.GetLength(0); i++)
{
for (int j=0; j<slots.GetLength(1); j++)
{
slots[i,0] = 1;
slots[i,j] = i+1;
}
}
int q = 0;
foreach (int i in slots)
{
if ((q%2) == 1)
Console.WriteLine(i + " ");
else
Console.Write(i + " ");
q++;
}
}
}
My final output is what I expect it. However, I want to fill each of the second column each time the user enters "a".
First enters "a"
1111 1000
Second time enters "a"
1111 1200
Third time enters "a"
1111 1230
Fourth time enters "a"
1111 1234
First of all,your for loop isn't as you want it,because before the user inputs "a" or "b" you already initialized in the for loop inside for loop,the array as it should be in the end.After the for loops the array is 1111 1234.
You can create a counter variable to count the number of times the user had entered "a" each time that you get the input.In this specific case there is a connection between the row of the array,and the amount of "a"'s the user has entered so I initialized the counter with 0 even though it value goes up only if you enter "a" again.The amount of "a"'s the user has entered-1 because it is 1 for sure after it gets into the forloop,so thats why you can also set it as the element of the array that you wanted to change.
Additionally,you can use while(true) instead of creating a variable and leave it the same.
Its pretty much like this:(Tried to use your way printing it)
int[,] slots = new int[4, 2];
string appt_type;
int counter = 0;//counts how many times the user had enter the letter "a"
while (true)
{
Console.WriteLine("Please enter a or b");
appt_type = Console.ReadLine();
if (appt_type == "a")
{
counter++;
for (int i = 0; i < slots.GetLength(0); i++)
{
for (int j = 0; j < slots.GetLength(1); j++)
{
slots[i, 0] = 1;
slots[counter - 1,1 ] = counter;//note:all of the elements that you want to change are in column 1 of the array
}
}
int q = 1;//the position of i in the array
foreach (int i in slots)
{
if(q%2!=1)
Console.WriteLine(i+" " );
else
Console.Write(i);
q++;
}
In order for your code to allow the user to input his/her choice and make the code do something based on that choice, you need to check the element's value if it is 0 or something else and then do something based on that value. Here is a quick untested fix, but you can get the gist:
for (int i=0; i<slots.GetLength(0); i++)
{
for (int j=0; j<slots.GetLength(1); j++)
{
if (slots[i,j] == 0)
{
slots[i,j] = i+1;
break;
}
}
}
I think your code can still be improved in a lot more ways. Here are my suggestions:
Break apart your code in methods to make it easier to read.
Separate the routines when A is selected, when B is selected, and
when slots is displayed.
It is clear that upon selecting choice A, the first column of the
array is set to 1111 and does not change up to the end, so set it
once and forget about going through it by checking if the first
element of the column is equal to 1.
You don't have to go through all of the elements in the second column
just to set the value. Just check for the first 0 that you encounter
and set it to the current index + 1.
Use break to get out of loops easily and eliminate the curly braces to
make the code look a bit cleaner.
Ignore the case when comparing strings, because a != A.
Here is a suggested and tested refactor. Add a break point on while(true), make it run in debug mode, and see how the code flows on every user input:
class Program
{
static void Main(string[] args)
{
var slots = new int[4, 2];
while (true)
{
Console.Write("Do you want to proceed? [Y/N]");
var choice = Console.ReadLine();
if (!choice.Equals("y", StringComparison.CurrentCultureIgnoreCase))
break;
Console.WriteLine("Please enter a or b: ");
var appt_type = Console.ReadLine();
if (appt_type.Equals("a", StringComparison.CurrentCultureIgnoreCase))
slots = AssignScheduleA(slots);
else if (appt_type.Equals("b", StringComparison.CurrentCultureIgnoreCase))
AssignScheduleB(slots);
DisplaySlotsValue(slots);
}
}
private static int[,] AssignScheduleA(int[,] slots)
{
if (slots[0,0] != 1)
{
for(int idx1 = 0; idx1 < slots.GetLength(0); idx1++)
slots[idx1, 0] = 1;
}
for(int idx2 = 0; idx2 < slots.GetLength(0); idx2++)
{
if (slots[idx2, 1] == 0)
{
slots[idx2, 1] = idx2 + 1;
break;
}
}
return slots;
}
private static void AssignScheduleB(int[,] slots)
{
throw new NotImplementedException();
}
private static void DisplaySlotsValue(int[,] slots)
{
for (int idx1 = 0; idx1 < slots.GetLength(0); idx1++)
Console.Write(slots[idx1, 0]);
Console.WriteLine();
for (int idx2 = 0; idx2 < slots.GetLength(0); idx2++)
Console.Write(slots[idx2, 1]);
Console.WriteLine();
}
}
If you go over this while on debug mode, you will understand how the code will let the user make a choice every time and fill in the array based on the choice. This code can still be improved and that can be something that you do as you learn more about C#. Happy coding!
I come from a C++ background creating basic 2D games with it, but I am trying to teach myself C# to a point to where I can get the most basic of jobs using it. I am not in school but I am following the Problems on ProjectEuler.net.
The problem question is commented into the code. I can't tell whether I solved it or not because I can't get the numbers to display from a list into the console application.
I've tried writing to console directly from the variable value with Console.WriteLine but I'm not having any luck. I've also tried converting all int list values to a string value and displaying them but that also didn't work.
I'm not looking for the answer to number 4 just looking to display the list so I can find the answer on my own.
Why can't I get the list to write to the Console?
Any help is appreciated!
static void Main(string[] args)
{
/* A palindromic number reads the same both ways.
* The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers. */
// 100 x 100 = 10000
// 999 x 999 = 998001
List<int> palindromeContainer = new List<int>();
int Increment = 2;
int Holder = 0;
for (int i = 100; i <= 999; ++i)
{
int j = i;
while (j <= 999)
{
do
{ Holder = i * j; // Gets all Possible Combinations of i * j
if ((Holder % Increment) != 0) // Checks for Prime Numbers
{
++Increment;
}
else if (Increment == Holder - 1 && Holder % Increment != 0 )
{
palindromeContainer.Add(Holder);
Increment = 2;
break;
}
else if (Increment == Holder - 1 && Holder % Increment == 0)
{
Increment = 2;
break;
}
} while (Increment < Holder);
++j;
}
}
palindromeContainer.Sort();
foreach (int line in palindromeContainer)
{
Console.WriteLine(line); // Display all items in list
}
Firstly comment out your loop logic and test without:
List<int> palindromeContainer = new List<int>();
palindromeContainer.Add(2);
palindromeContainer.Add(1);
palindromeContainer.Sort();
foreach (int line in palindromeContainer)
{
Console.WriteLine(line); // Display all items in list
}
Console.ReadLine();
This will output to the console. Then you will know this is working and console output is not the problem.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
First post here so tell me if I did something wrong :)
So I have this code:
static void Main(string[] args)
{
//declaring first array
Console.Write("Enter the size of the first the array: ");
int sizeOne = Int32.Parse(Console.ReadLine());
int[]firstArray = new int[sizeOne];
//fill it from console
for (int counter = 0; counter<=sizeOne - 1; counter++)
{
Console.Write("Please enter a value: ");
firstArray[counter] = Int32.Parse(Console.ReadLine());
//for test
// Console.WriteLine(firstArray[counter]);
}
//declaring second array
Console.Write("Enter the size of the second array: ");
int sizeTwo = Int32.Parse(Console.ReadLine());
int[] secondArray = new int[sizeTwo];
//fill it from console
for (int counter = 0; counter <= sizeTwo - 1; counter++)
{
Console.Write("Please enter a value: ");
firstArray[counter] = Int32.Parse(Console.ReadLine());
//for test
// Console.WriteLine(secondArray[counter]);
}
//compare size and values, as sidenote it could write not equal even
//when the user inputs two arrays with different lengths to save time :)
if (firstArray.Length == secondArray.Length)
{
for (int counter = 0; counter <= sizeOne; counter++)
{
if ((firstArray[counter]) != (secondArray[counter]))
{
Console.WriteLine("The two arrays aren't equal");
break;
}
else
{
Console.WriteLine("The two arrays are equal");
}
}
}
else
{
Console.WriteLine("The two arrays aren't equal");
}
}
It should compare the arrays by length, and elements. It does if two arrays have different length but at equal number of elements it always writes not equal. What did I miss?
Thank you for help in advance!
It's a typo, or copy-paste error, whatever you want to call it. In your 2nd loop, when you are supposed to populate secondArray, you are populating firstArray by mistake. This means that secondArray only ever has zeroes. You probably got lucky (or unlucky) that firstArray was always equal or larger in size than secondArray. Otherwise you would have gotten an exception, which may have helped you to spot your mistake.
Note that once you fix it, you will also get an out of bounds exception, because your comparing loop uses the counter <= sizeOne condition, which is wrong. It should be counter < sizeOne, otherwise you will go past the end of the array.
Just modify the loop a bit:
You need a Boolean flag, that indicates if there are mismatches. Otherwise it would print "The two arrays are equal" if just the first element(s) matches.
if (firstArray.Length == secondArray.Length)
{
bool areEqual = true;
for (int counter = 0; counter < firstArray.Length; counter++)
{
if ((firstArray[counter]) != (secondArray[counter]))
{
areEqual = false;
//Console.WriteLine("The two arrays aren't equal");
break;
}
// This would get executed if the first elements are equal, but others are not
//else
//{
// Console.WriteLine("The two arrays are equal");
//}
}
if (areEqual)
Console.WriteLine("The two arrays are equal");
else
Console.WriteLine("The two arrays aren't equal");
}
And then there is of course a build in function (in .NET) called SequenceEqual that does compare two arrays:
using System.Linq;
...
bool areEqual = firstArray.SequenceEqual(secondArray);
if (areEqual)
Console.WriteLine("The two arrays are equal");
else
Console.WriteLine("The two arrays aren't equal");
See NetFiddle
There is also a Typo: You're filling the firstArray twice.
//fill it from console
for (int counter = 0; counter <= sizeTwo - 1; counter++)
{
Console.Write("Please enter a value: ");
// **Must be secondArray**
firstArray[counter] = Int32.Parse(Console.ReadLine());
//for test
// Console.WriteLine(secondArray[counter]);
}
I have a method that needs to do a calculation based upon the length of an array. I am using the .length method for the calculation, but the method is doing arithmetic with the max length of the array (which I have declared as 10). This is the loop I am using to get data from the user. I know it isn't the ideal way to sort array data, but this is for a homework assignment, and it revolves around using the .Split method correctly (which isn't the problem I'm having).
for (int i = 0; i < MAX; i++)
{
Console.Write("Enter a name and a score for player #{0}: ", (i + 1));
string input = Console.ReadLine();
if (input == "")
{
// If nothing is entered, it will break the loop.
break;
}
// Splits the user data into 2 arrays (integer and string).
string[] separateInput = input.Split();
name [i] = separateInput[0];
score [i] = int.Parse(separateInput[1]);
}
Here is the method I am using to calculate the average score:
static void CalculateScores(int[] score)
{
int sum = 0;
int average = 0;
for (int i = 0; i < score.Length; i++)
{
sum += score[i];
average = sum / score.Length;
}
Console.WriteLine("The average score was {0}", average);
I am calling the method like this:
CalculateScores(score);
Edit: My arrays are declared:
int[] score = new int[MAX]; //MAX == 10.
string[] name = new string[MAX];
The CalculateScores method is doing the math as though score.Length is always 10, no matter how many different combinations of scores I input to the console. I can't figure out if it's because my loop to gather input has been done incorrectly, or my CalculateScores method is flawed. Thanks in advance.
Edit: to clarify, I am just confused at why I can't get the correct value out of CalculateScores.
Length always represents the size of the array, which if you've instantiated as 10, then it will always be 10, regardless of how many items you've filled.
There are lots of ways of solving your problem, but I'd go with the simple one of not using length in your calculation, but rather just storing the number of items in a separate variable:
int numItems = 0;
for(int i=0;i<MAX;i++)
{
Console.Write("Enter a name and a score for player #{0}: ", (i + 1));
string input = Console.ReadLine();
if (input == "")
{
break; // if nothing is entered, it will break the loop
}
numItems++;
...
}
static void CalculateScores(int[] score, int numItems)
{
// don't use Length at all, use numItems instead
}
Arrays are generally used for fixed sized data, so the Length property reflects how many items the array can hold rather than the amount of elements in the array. The simplest fix would be to use a List(T), which is used for variadic data, instead.
// A nice abstraction to hold the scores instead of two separate arrays.
public class ScoreKeeper
{
public string Name { get; set; }
public int Score { get; set; }
}
var scores = new List<ScoreKeeper>();
for (int i = 0; i < MAX; i++)
{
Console.Write("Enter a name and a score for player #{0}: ", (i + 1));
string input = Console.ReadLine();
if (input == "")
{
// If nothing is entered, it will break the loop.
break;
}
// Splits the user data into 2 arrays (integer and string).
string[] separateInput = input.Split();
scores.Add(new ScoreKeeper { Name = separateInput[0], Score = int.Parse(separateInput[1]) });
}
static void CalculateScores(ICollection<ScoreKeeper> scores)
{
// We take advantage of Linq here by gathering all the
// scores and taking their average.
var average = scores.Select(s => s.Score).Average();
Console.WriteLine("The average score was {0}", average);
}
checking maually:
int sum = 0;
int average = 0;
int length;
for (int i = 0; i < MAX; i++) {
if(name[i]!=string.empty) {
sum += score[i];
length=i+1;
}
}
average = sum / length;
Console.WriteLine("The average score was {0}", average);