So I'm having a couple of troubles with my code. For starters, I have this problem which is outputting all of the arrays. Mind you I have only been coding for 12 days and my teacher has somewhat skipped over the very basics in C# coding due to my college's outlook on learning. AND I just learned that it doesn't order them alphabetically.....
static int inputPartInformation(string[] pl)
{
int i = 0;
do
{
Console.Write("Enter a Name: ");
//for the player
pl[i] = Console.ReadLine();
}
while (pl[i++].CompareTo("Q") != 0);
//if they write Q for the player it will quit
return i - 1;
}
static void Main(string[] args)
{
String[] players = new String[100];
Array.Sort(players);
// Sort array.
//defines players in this new instance
var count = inputPartInformation(players);
//for the portion of the code that handles the input
//calculates the average score
Console.WriteLine("List of People in Order: {0}, {1}, {2}, {3}, {4}, {5}, {6},", players);
Console.ReadLine();
}
}
}
You are sorting before the names are populated; that does nothing.
You are printing a single item using a fixed multi-item list of parameter references {0}, {1},{2} and so on; it is not going to work, and even if it did it would limit your output to the first seven items
You do not know how many items to sort. Change void inputPartInformation(string[] pl) to return count (which is i-1), and use Array.Sort(players, 0, count);
The simplest way to convert multiple strings into a single string is by using string.Join:
Console.WriteLine("List of People in Order: {0}", string.Join(", ", players.Take(count)));
First, "Q" is being added to the input list because you don't test for "Q" until after the input has been accepted and inserted into your array. One way of reworking this would be to hold the input name into a temporary variable, test that for "Q", and add it to your array only if it is something else. Within your loop, modify your input/test to something like:
bool enteringNames=true;
do{
String nextName = Console.ReadLine();
if (nextName.CompareTo("Q")==0)
{
enteringNames=false;
}
else
{
p[i]=nextName;
}
i++;
}
while(enteringNames);
This is just one way of getting the job done. Keep in mind that a fixed 100-entry array isn't the most robust way of doing this...never know how many names might be going in!
Now, the last WriteLine is a bit odd, but I think you can figure that part out on your own - its pretty straightforward to either iterate through the array, or just join all the strings together :)
Second, your sort isn't working because you call Array.Sort(players) before you call inputPartInformation(players) to actually load the data - so you're sorting without any data!. Move the Array.Sort call after the call to inputPartInformation.
Hope this helps!
Try this, it will work, but first try to study about the APIs
static int inputPartInformation(string[] pl)
{
int i = 0;
String temp;
while (true)
{
Console.Write("Enter a Name: ");
temp=Console.ReadLine();
if (temp=="Q")
break;
else pl[i++] = temp;
}
return i;
}
static void Main(string[] args)
{
String[] players = new String[100];
int size=inputPartInformation(players);
for (int i = 0; i <= size; i++)
Console.WriteLine(players[i]);
}
}
Q is appearing in your outcome because you are assigning it to your array.
Rewrite you function to check the value before you assign it, for example
static void inputPartInformation(string[] pl)
{
int i = 0;
do
{
Console.Write("Enter a Name: ");
//for the player
newStrInput = Console.ReadLine();
if (newStrInput == "Q")
break;//if they write Q for the player it will quit
pl[i]=newStrInput;
i++;
}
while (i>-1);//infinite loop
}
Related
My first post on here! I started learning how to program a couple of days ago and have picked up a rolling dice project. I think I have done the main part of it but my problem comes from:
Printing how many times each side came up (maybe store them in an array)?
Bonus: Print out the percentage of times each side appeared (rounded up to 2 decimals)
Keep in mind the times and sides are user input so could be e.g. 50 times x 35 sides.
using System;
using System.Collections.Generic;
using System.Security.Cryptography.X509Certificates;
namespace Dice_roll
{
class Program
{
static void Main(string[] args)
{
static int getRandomNumber(int min, int max)
{
Random randomRoll = new Random();
lock (randomRoll)
{
return randomRoll.Next(min, max);
}
}
int sides, rollTimes, i;
i = 0;
bool boolCheckSides = false;
bool boolCheckRolls = false;
Console.WriteLine("Welcome to a little dice rolling program.\n Select how many sides you want the dice to have: \n");
do
{
boolCheckSides = Int32.TryParse(Console.ReadLine(), out sides);
if (boolCheckSides == false)
{
Console.WriteLine("Invalid number.. \n");
}
} while (boolCheckSides == false);
Console.WriteLine("Now select how many times you want it to roll: \n");
do
{
boolCheckRolls = Int32.TryParse(Console.ReadLine(), out rollTimes);
if (boolCheckRolls == false)
{
Console.WriteLine("Invalid number.. \n");
}
} while (boolCheckRolls == false);
do
{
Console.WriteLine("Rolling... " + getRandomNumber(1, sides));
i = i + 1;
System.Threading.Thread.Sleep(500);
} while (i < rollTimes);
int[] arr = new int[rollTimes];
}
}
}
I'm sorry if my code is messy or something, I'm still very beginner.
Well, I assume that your code is not complete yet, so I will just share some opinions of mine.
1- You are adding a method getRandomNumber inside your main function. This method won't compile and should be moved outside the scope of main function. The scope of main function is any code between the curly brackets "{}" shown in the code below
static void main(string[] args){}
just a small side note, try to use Uppercase letters for naming methods in C#, except the main function as that's a naming convention ;-)
2- You did a great job in declaring the variables you need (boolCheckSides, boolCheckRolls, i) before you start assigning them values. However, you also need to declare the Array before using it not after, so your code should look something like this
//Declare the Array
int[] arr = new int[rollTimes];
do
{
int temp = getRandomNumber(1, sides);
Console.WriteLine("Rolling... " + temp);
//Save the value acquired from this roll in the array
arr[i] = temp;
i = i + 1;
System.Threading.Thread.Sleep(500);
} while (i < rollTimes);
Then you can easily play around with the array and find the frequency of any number. I would suggest you refer to this post Count the frequency of element of an array in C# if you want to find the short answer, and refer to this post Frequency of Numbers in a 1D Array for the long answer. Just please note that the second post is using C++ language, but it is still showing the same logic though.
3- Just a small advise, please try to avoid "do...while" loops as much as possible. It needs a lot of attention when you write them as they can easily get you into infinite loop.
I suggest you to use a Dictionary, with the side (1 to X) as Key and number of time its appears .
class Program
{
Dictionary<int, int> RollDice = new Dictionary<int, int>();
static void Main(string[] args)
{
:
Console.WriteLine("Welcome to a little dice rolling program.\n Select how many sides you want the dice to have: \n");
do
{
boolCheckSides = Int32.TryParse(Console.ReadLine(), out sides);
if (boolCheckSides == false)
{
Console.WriteLine("Invalid number.. \n");
}
} while (boolCheckSides == false);
//Initialize the dictionary with key and value
for(int i = 1; i<=sides;i++)
RollDice.Add(i, 0);
:
i = 0;
do
{
var value = getRandomNumber(1, sides + 1)
Console.WriteLine("Rolling... " + value);
RollDice[i]++;
i = i + 1;
System.Threading.Thread.Sleep(500);
} while (i < rollTimes);
and you could display your stats by looping over the dictionary:
foreach (var pair in RollDice)
{
Console.WriteLine($"DiceSide:{pair.Key} , appears: {pair.Value}, probability: {(float)pair.Value/(float)rollTimes:0.00}");
}
I have an assignment that requires us to use arrays and not lists. I have two problems right now; one being that every time the user makes an input, the length of array playerNumber increases by one so I need it to be indefinite and I also need to send the array back to the main method. The code below works only once and when I try to enter a second input the program crashes.
int x = 0;
string answer = "yes";
string[] playerNumber = new string[] {};
while (answer == "yes")
{
Console.Write("Enter a number : ");
string y = Console.ReadLine();
playerNumber = new string[] { y };
playerNumber[x - 1] = y;
x++;
Console.Write("Enter another number : ");
answer = Console.ReadLine();
Console.WriteLine();
}
It is not clear what your'e trying to do.
To start with, your index is out of bounds.
Your'e doing: playerNumber[x-1], but x == 0, so you get an exception. This is the only reason your code fails. Note that taking the ++x; one line up will also fail you, since in the second loop, playerNumber is again an array of size 1, but x value is now 2, and your'e again out of bounds.
Secondly, your'e initializing your array both outside and inside the while loop. You have no use of the outer initialization (and maybe there's no need for the inner one - again, depends on what exactly you're trying to achieve).
Thirdly, you should give the user the correct instruction: If you want answer to be yes or no, specify it in your Console.Write.
So if I managed to guess what you were trying to do, here's your code with a few changes, including the usage of Array.Resize (which is very inefficient in this context), and returning the array, as you asked:
using System;
public class Test
{
public static string[] MyFunc()
{
int x = 1;
string answer = "yes";
string[] playerNumber = new string[x];
while (answer == "yes")
{
Console.Write("Enter a number : ");
string y = Console.ReadLine();
playerNumber[x-1] = y;
x++;
Array.Resize(ref playerNumber, x);
Console.Write("Would you like to enter another number? (yes/no)");
answer = Console.ReadLine();
Console.WriteLine();
}
return playerNumber;
}
public static void Main()
{
Console.WriteLine(MyFunc()[0]); // prints the first string
}
}
I am very confused on how to change a for loop into a foreach loop. I have a piece of code that is similar to a program that I working on to implement a foreach loop into.
{
class Program
{
static void Main(string[] args)
{
int entered = 0;
string ayethatsprettygood;
bool dothesalamander = false;
string[] zipcode;
zipcode = new string[10] {"12789", "54012", "54481", "54982", "60007", "60103", "60187", "60188", "71244", "90210" }; //This array is the zipcodes
double[] prices;
prices = new double[10] { 2.40, 3.00, 3.50, 4.00, 4.50, 5.00, 5.25, 5.75, 6.10, 10.003 }; //This array is the prices
Console.Write("Enter a Zipcode:");
ayethatsprettygood = Console.ReadLine();
for (int i = 0; i < zipcode.Length; i++) {
if (ayethatsprettygood == zipcode[i])
{
dothesalamander = true;
entered = i;
break;
}
}
if (dothesalamander == true)
{
Console.WriteLine("We deliver to this zipcode {0} the price of delivery is {1}", zipcode[entered], prices[entered].ToString("C2"));
}
else
Console.WriteLine("We don't deliver to this zipcode {0}",ayethatsprettygood);
{
class Program
{
static void Main(string[] args)
{
int entered = 0;
string ayethatsprettygood;
bool dothesalamander = false;
char[] pizzasize;
pizzasize = new char[4] { 'S', 'M', 'L', 'X' }; //This array is the zipcodes
double[] pizzaprices;
pizzaprices = new double[4] { 6.99, 8.99, 12.50, 15.00 }; //This array is the prices
Console.Write("Enter a Pizza Size:");
ayethatsprettygood = Console.ReadLine();
foreach(char pizzaprice in pizzaprices )
{
if (ayethatsprettygood == pizzaprice)
{
dothesalamander = true;
entered = pizzaprice;
break;
}
}
if (dothesalamander == true)
{
Console.WriteLine("The size of the pizza is {0} the price is {1}", pizzasize[entered], pizzaprices[entered].ToString("C2"));
}
else
Console.WriteLine("Sorry you entered an invalid size {0}", ayethatsprettygood);
}
}
}
if anyone could help me complete this program it would be really helpful!
Thank You!
With an ordinary for loop, you manage the index yourself, and if you are iterating through an array, you have to use the index to look up items.
var a = new string[] {"This","Is","An","Array"};
for (var i = a.GetLowerBound(0); i <= a.GetUpperBound(0); i = i + 1)
{
var s = a[i];
Console.WriteLine(s);
}
With a foreach loop, the framework uses a special interface (IEnumerable) to do the iteration and lookup for you:
var a = new string[] {"This","Is","An","Array"};
foreach (var s in a)
{
Console.WriteLine(s);
}
Most arrays, lists, dictionaries, and other types of collections implement IEnumerable, so you can use this technique to go through most lists. If IEnumerable isn't available, you can't use foreach.
The foreach construct requires less typing, and iterations can run in parallel (using Parallel.ForEach), so it has some advantages. The main disadvantage is that there is no guarantee what order the elements will be processed, plus you no longer have access to a variable that has the index in it. This could be an issue in certain cases, e.g. copying data between two arrays, where order might be important.
Also, while using the enumerator, deleting and adding items is highly discouraged if not outright impossible due to confusion it can introduce.
foreach is not a very good choice when you are utilizing parallel arrays (hint, parallel arrays are not actually used all that often, or ever, in "real" code).
The reason is, as you discovered, that you have no idea what a given item's index is (foreach does not guarantee linear traversal, though it often is in practice). Here are three ways of solving the problem:
Assume Linear Traversal
You can setup a counter outside of the loop and increment it with every iteration. Assuming that foreach starts at index 0 and increments by 1, you will still have your index:
int iterationIndex = 0;
foreach (item in collection)
{
iterationIndex++;
}
Of course, if the assumption is wrong (in practice, traversal is usually linear, and always is on arrays and lists) then your code will break.
Search the array
You know which item you are looking for; you can use an array/list method to get its index:
int index = collection.IndexOf(item);
var parallelItem = parallelCollection[index];
This breaks down if collection has multiple instances of item (effectively a duplicate key).
Use a class (Correct answer!)
All of this is moot if you discard parallel arrays and use objects. Say I have a pizza class:
public class Pizza
{
public double Size {get; set}
public double Price {get; set;}
}
Now the data association is handled by the framework and I can write:
Pizza requestedPizza;
foreach (Pizza pizza in allPizzas)
{
if (pizza.Price == enteredPrice)
{
requestedPizza = pizza;
break;
}
}
Console.WriteLine($"Found pizza size {requestedPizza.Size} that matches price {requestedPizza.Price}");
For future use, that whole foreach is totally unnecessary, LINQ will write it for us:
Pizza requestedPizza = allPizzas.FirstOrDefault(p => p.Price == requestedPrice);
Hi there I'm very new to C# so please bear with me if my question has a very obvious answer.
I am trying to write a code that displays an array of options to the user with a number to select the option. The user then selects their option and the code will display their selection from the array.
So for example
Select 1 for apples
Select 2 for oranges
Select 3 for pears
Please Enter your Selection :
I keep typing a for loop to display my area but I cannot get my program to read the input from the array this is what I have so far
static void Main(string[] args) {
string[] fruit = [3]
fruit[0]=("apples");
fruit[1]=("oranges");
fruit[2]=("pears");
for (int i = 0; i < fruit.length; i++)
{
Console.WriteLine("Enter {0} to select {1}", i, fruit[i]);
}
string choice = Console.ReadLine();
int i = int.Parse(choice);
Console.WriteLine("You have selected {0} which is {1}", i, fruit[i]);
Console.ReadLine();
}
This gives me an error and if I place this within the for loop then the program does not display me all my options.
Multiple problems with your code:
Define your string array like string[] fruit = new string[3];
Since you have defined i in your for loop, you need to use a new variable for your input.
Your condition in for loop should be i < fruit.Length
This is more of a suggestion, use int.TryParse to parse input from console, check if the entered number is an int and also check if the number is less than the array length.
You need to give different name to your loop variable or the user choice.
Also you might want to use TryParse intead of Parse to prevent possible FormatExceptions:
int userChoice;
if(int.TryParse(choice, out userChoice) && userChoice < fruit.Length)
Console.WriteLine("You have selected {0} which is {1}", userChoice, fruit[userChoice]);
void Main()
{
// compile a list of possible fruits (remember that c# arrays are
// 0-indexed (first element is actually 0 and not 1))
string[] fruits = new[]{
"apples",
"oranges",
"pears"
};
// iterate over the options and output each one
for (var i = 0; i < fruits.Length; i++){
// add one to index value to make it non-0 based
Console.WriteLine("Enter {0} to select {1}", i + 1, fruits[i]);
}
// continue to read user input until they select a valid choice
Int32 choice = 0;
do
{
// read user input
String input = Console.ReadLine();
// [try to] convert the input to an integer
// if it fails, you'll end up with choice=0
// which will force the while(...) condition to fail
// and, therefore, retry for another selection.
Int32.TryParse(input, out choice);
}
// number should be between 1 and (fruits.Length + 1)
while (choice < 1 || choice > (fruits.Length + 1));
// to reference it, subtract 1 from user's choice to get back to
// 0-indexed array
Console.WriteLine("You have selected {0} which is {1}", choice, fruits[choice - 1]);
}
You have multiple typos and you can't use the variable i twice.
Try this:
static public void Main(string[] args)
{
string[] fruit = new string[3];
fruit[0]=("apples");
fruit[1]=("oranges");
fruit[2]=("pears");
for (int i = 0; i < fruit.Length; i++)
{
Console.WriteLine("Enter {0} to select {1}", i, fruit[i]);
}
string choice = Console.ReadLine();
int j = int.Parse(choice);
Console.WriteLine("You have selected {0} which is {1}", j, fruit[j]);
Console.ReadLine();
}
You might also want to include some error trapping if the user enters something that can't be parsed as an int (you could use TryParse for example).
Typos: Your array declaration was wrong and you need a captial L on length for the array length property.
Your string array declaration is incorrect. Try
string[] fruit = new string[3];
or you can declare and initiate thus:
string[] fruit = new string[3]{"apples", "oranges", "pears"};
or simpler:
string[] fruit = {"apples", "oranges", "pears"};
Ok guys, im just starting C# and trying to transition from the basic side of C++.
I'm working on a lesson(not for a grade, it is a learning assignment), and I have everything set up except for getting the user input. I am trying to use a list instead of an array but I can't figure out how to get it to let the user enter the prices.
This is a project for a simple register. The user has to enter the price. And here will be less than 100 items.
This is what I have so far:
static void Main()
{
double i;
Console.Writeline("Enter Item Prices\n");
List<double> items = new List<double>[i];
Console.ReadLine(items);
Console.WriteLine("{0}: ", i, items[i]);
for (double i = 0; i < 100; i++)
{
items.Add(i);
}
return 0;
}
I have all the calcs set up, just can't get the input needed for the prices. I know some things with i are wrong. Also, its the WriteLine and ReadLine taking the place of cout and cin that is messing me up I think.
I just need to figure out how to get the prices and get them put into my formulas.
I will give the best answer props for helping in my program comments.
Edit:
I need it to go back and check if the user want to continue or not
The order is a bit messed up. Fixed it for you:
Console.Writeline("Enter Item Prices\n");
List<double> items = new List<double>();
for (double i = 0; i < 100; i++)
{
string userInput;
double newItem;
// repeatedly ask for input from the user until it's a valid double
do
{
Console.Write(string.Format("Enter item #{0}: ", i));
// read from console into userInput
userInput = Console.ReadLine();
} while (!double.TryParse(userInput, out newItem))
// add the new item to the array
items.Add(newItem);
}
// output all the items to the console, separated by commas
Console.WriteLine(
string.Join(", ",
items.Select(item => item.ToString())
)
);
Minimal example.
class Program
{
static void Main(string[] args)
{
//reading the input and assign it to s
string s = Console.ReadLine();
//writing the input
Console.WriteLine(s);
}
}
You can add multiple items (from user input) separated by space into a list as follows:
string[] arrItems = Console.ReadLine().Split(' ');
List<double> lstItems = new List<double>(Array.ConvertAll(arrItems, arrTemp =>
Convert.ToDouble(arrTemp)));