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
}
}
Related
So this is a very simple code that i can for the love of me get right because of some small mistake but the point here is the first int the user gives is the amount of numbers you will give after it so i have made this but for some reason the program wants 1 more int than it should. Lets say i enter 3 at first. That should mean that it would take 3 ints after that and then print them and end the program but fore some reason if i enter 3 after that it wants 4. if i enter 4 after that it wants 5 and you get the point. I have tried changing the whole code but i think the problem is that i am just making it to long and to complicated. here is the code
using System;
namespace Homework_PrPr
{
class Program
{
static void Main(string[] args)
{
int ammount = int.Parse(Console.ReadLine());
int Enters = int.Parse(Console.ReadLine());
int[] numbers = new int[ammount];
for(int i = 0; i < ammount; i++)
{
numbers[i] = Enters;
Enters = int.Parse(Console.ReadLine());
}
int ammountEntered = 0;
while(ammountEntered < ammount)
{
Console.WriteLine(numbers[ammountEntered]);
ammountEntered++;
}
}
}
}
int ammount = int.Parse(Console.ReadLine());
int Enters = int.Parse(Console.ReadLine());
Take a moment to think about this. If the user enters amount = 1, what would Happen? You would first ask a number, then enter the loop one time, where it asks for another number. Why is it asking for another number in this case? Why not just skip the Enter variable and assign numbers inside the loop?
for(int i = 0; i < ammount; i++)
{
numbers[i] = int.Parse(Console.ReadLine());
}
I would highly recommend reading eric lipperts article on How to debug small programs, since problems like this should be very easy to diagnose when stepping thru a program. You might also consider reading the coding convensions guide, local variables should for example use "camelCasing".
You might also consider using a foreach loop when printing variables:
foreach(var number in numbers){
Console.WriteLine(number);
}
I think i understand your code!
This is how i would do it, and do read my explanation down below aswell!
using System;
namespace Homework_PrPr
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("How many numbers do you want to add to your array?");
int amount = int.Parse(Console.ReadLine());
int[] numbers = new int[amount];
for (int i = 0; i < amount; i++)
{
Console.WriteLine($"Numer {i+1}/{amount}"); // Just tells the user what I of number their adding. aka unessecary
int Enters = int.Parse(Console.ReadLine());
numbers[i] = Enters;
}
Console.WriteLine("\n");
int ammountEntered = 0;
while (ammountEntered < amount)
{
Console.Write($"Number {ammountEntered + 1}/{amount} : ");
Console.WriteLine(numbers[ammountEntered]);
ammountEntered++;
}
}
}
}
The first problem was that you asked for a unnesecary ReadLine in the beggining, so that i removed! Then inside you for-loop i switched the position of the adding, aswell as the one asking for a new number. I also added a few counters so that you can see a bit more in detail what the code does!
So I am currently pretty confused (keep in mind im new to coding).
I am currently trying to create a program which creates allows the user to input the amount of numbers they would like to enter in the array (it then creates an array based on that length), asks the user to input the numbers into their desired position.
My code currently looks like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Arrays
{
class Program
{
static void Main(string[] args)
{
//Variables
int[] array1 = new int[0];
int TotalArray, position, Number;
//Main Program
Console.WriteLine("Hello, welcome to creating your own array!");
Console.WriteLine("How many numbers do you wish to add to the array?: ");
TotalArray = int.Parse(Console.ReadLine());
Console.ReadKey();
{
Console.WriteLine("What position would you like to add your number to?: ");
position = int.Parse(Console.ReadLine());
if (position < TotalArray)
{
Console.WriteLine("What number would you like to add to position " + position);
Number = int.Parse(Console.ReadLine());
array1[position] = Number;
Console.WriteLine("Testing: " + array1[position]);
Console.ReadKey();
}
else
{
Console.WriteLine("Error! You entered your position higher than your total array!");
}
}
}
}
}
However, I do not understand how to create an array length based on the users input.
I have to tried to do this:
Console.WriteLine("Hello, welcome to creating your own array!");
Console.WriteLine("How many numbers do you wish to add to the array?: ");
TotalArray = int.Parse(Console.ReadLine());
int i = Convert.ToInt32(TotalArray);
int[] array1 = new int[i];
But get this error:
A local variable or function named 'array1' is already defined in this scope
I don't really understand what this piece of code does:
int i = Convert.ToInt32(TotalArray);
int[] array1 = new int[i];
However, I saw it mentioned on stackoverflow and thought id try an implement it. I kinda understand the 2nd line but don't really get the whole converting thing.
Any help would greatly be appreciated!
First, you don't need to convert TotalArray to an integer, since you already parsed the user's repsonse as an integer. So omit i. Next, you're declaring a new array1. Instead, just assign a new one to the same reference:
array1 = new int[TotalArray];
As for the loop. Here's the naive version, but if you need to scold the user for picking the same position twice, you'll need to do a lot more work.
int requestCount = TotalArray;
while (requestCount > 0)
{
requestCount = requestCount - 1;
Console.WriteLine("What position would you like to add your number to? (0 - "
+ (TotalArray - 1) + "): ");
position = int.Parse(Console.ReadLine());
if (position < TotalArray)
{
Console.WriteLine("What number would you like to add to position " + position);
Number = int.Parse(Console.ReadLine());
array1[position] = Number;
Console.WriteLine("Testing: " + array1[position]);
Console.ReadKey();
}
else
{
Console.WriteLine("Error! You entered your position higher than your total array!");
}
}
first this is the right way to write your code
Console.WriteLine("Hello, welcome to creating your own array!");
Console.WriteLine("How many numbers do you wish to add to the array?: ");
TotalArray = int.Parse(Console.ReadLine());
array1 = new int[TotalArray];
the third line means read the last line entered into the console then convert it to a value of type int, then store this value in the variable TotalArray
while the fourth line means construct a new array of length TotalArray then store the resulted array into the variable array1
this doesn't work when you write int[] array1 = new int[i]; because it means create a new variable called array1 then create a new array of length i to be stored in the newly created variable array1
and as you can see in your code you've already defined array1
here:
//Variables
int[] array1 = new int[0];
this is why you get the message: A local variable or function named 'array1' is already defined in this scope
but good job for a beginner.
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"};
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
}
In general, I know that int32 errors mean that a string value is not getting converted for the console program. I have seen a lot of code trying to find the answer to this including the following stackoverflow questions (seen much more but these were most useful:
How to sum up an array of integers in C#
Error CS1501: I'm not overloading a Sum() method correctly
CS0019 Operator cannot be applied to operands of type 'bool' and 'int'
That being said, this is also a homework assignment, titled UsingSum.cs as seen in a couple of these links. The difference in mine and these is that I am trying to make it so that the user enters however many Integers they want, then they are added up. The entire assignment is written in link 2....
The problem: I keep getting either 0 or System.Int32[] instead of the sum, despite the changes I make.
I cannot use Linq.
Here is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace UsingSum
{
class Program
{
static void Main(string[] args)
{
int i;
int usrInput;
bool running = true;
//Enter Question Asking Loop w/ running=true
while (running)
{
Console.Write("Enter a number or enter 999 to exit: ");
int[] array1 = new int[0];
for (i = 0; i < array1.Length; i++)
{
usrInput = Convert.ToInt32(Console.ReadLine());
array1[i] = Convert.ToInt32(usrInput);
}
for (i = 0; i < array1.Length; i++)
{
Console.WriteLine(array1[i]);
}
/*If the user enters 999, calls Sum() and asks user to press any key to exit.
changes 'running' from true to false to exit the question loop*/
int exit = Convert.ToInt32 (Console.ReadLine());
if (exit == 999)
{
running = false;
Sum(array1);
}
}
//Loop complete
Console.WriteLine("Press any key to exit.");
Console.ReadLine();
}
public static void Sum(int[] numbers)
{
int [] sum1 = new int [0];
int sum2 = 0;
//Program accepts user responses with or w/o this loop...Int.32 error present both ways
//for (int a = 0; a < numbers.Length; ++a)
//sum1[a] = a;
//additional loop tried w/o the loop above/below;
//when used in the WriteLine w/ sum2 it displays 0, when used with sum1 or numbers Int.32 error
//Array.ForEach(sum1, delegate(int i) { sum2 += i; });
foreach (int i in numbers)
sum2 =+ i;
Console.WriteLine("The sum of the values in your array is: " + sum1);
/*tried changing 'numbers' to sum1, sum2, sum1.Convert.ToString(),sum2.Convert.ToString()
numbers.Convert.ToString(), also tried converting sum2 to a string.*/
}
}
}
Here is my final solution!
static void Main(string[] args)
{
AskUserForNumbers();
Console.WriteLine("Press any key to exit");
Console.ReadLine();
}
public static List<Int32> AskUserForNumbers()
{
bool running = true;
List<int> numbers = new List<int>();
while (running)
{
Console.Write("Enter a number or enter 999 to exit: ");
int inputValue;
var inputString = Console.ReadLine();
//Check for "999" which indicates we should display the numbers entered, the total and then exit our loop.
if (inputString == "999")
{
Console.WriteLine("The sum of the values in your array is: " + numbers.Sum());
running = false;
}
else if (Int32.TryParse(inputString, out inputValue) && inputValue > 0)
{
numbers.Add(inputValue);
}
else
{
Console.WriteLine("Please enter a whole number greater than 0");
}
}
return numbers;
}
}
}
A few problems:
First, you're always declaring your arrays as int[] array1 = new int[0];. This means that your code for actually getting the user input will never hit. Maybe you should try using a different collection type (List<int> maybe).
Second, you never perform any error checking when parsing the integer. That's bad practice. You should be using int.TryParse(string input, out result) to verify it was a valid number before adding it to the array.
Third, you are looping over the length of the array for inputs, meaning you will loop through however long the array is, and will continue doing so until the last input you have is the exit number (999).
Fourth, the input you get for the exit code is discarded (not added to the array to sum).
Just remember that programming is very procedural. There should be clear (logical) steps from point a to point b. In fact, imagine you are the program and you're asking a friend to give you numbers to sum up for him. Give him whatever information you think might be useful (such as the exit condition). Diagram the steps, and then try to translate that to code.
Edit: The main point is that an array (which has a fixed size) is NOT the tool for the job here. You're not actually filling the array with any data, so that's why the sum never happens. The culprit is here:
int[] array1 = new int[0]; // Instantiate a zero-length array? Can't hold any values
// Will never hit inside the loop here, because i < array1.Length (which is zero) will always be false.
for (i = 0; i < array1.Length; i++)
You need to either increase the size of the array to begin with (and either reuse the indexes or resize the array) or use an non-fixed collection (List, for example). Finally, when you pass array1 to the Sum method, array1 is empty because you declared it as a zero element array. That is why you always get a zero printing out. Like I said before, imagine you are the program, and actually run through all these steps, LINE BY LINE.
For example, you start in the loop. You prepare a miniature notebook to write down all the numbers your friend is telling you with no pages in it. For every page (and realize there are none) in the notebook, you ask your friend for a number. After you've gone through every page, you now go through every page again to read all the values he gave you (keep in mind he couldn't give you any numbers, since the notebook was empty). Then you ask him one more time for a number, and if it's 999 you tell him you're done and give him the sum of all the numbers you wrote down. If he didn't give you 999 as the number, you repeat the cycle.
Do you understand WHY it's not working now?
public static void Sum(int[] numbers)
{
int sum2 = 0;
foreach (int i in numbers)
sum2 =+ i;
Console.WriteLine("The sum of the values in your array is: " + sum2);
}
foreach (int i in numbers)
sum2 =+ i;
should become
foreach (int i in numbers)
sum2 += i;
Your problem is with your first for loop. You never will add items to your array because your
for (i = 0; i < array1.Length; i++)
Since you only add to your array1 array when you enter the loop, it won't ever increment. Since i = 0 and the array1.Length is 0 to start, i will never be less than the length.
Here is what I would suggest you do.
private static void Main(string[] args) {
var running = true;
var numbers = new List<int>();
//Enter Question Asking Loop w/ running=true
while (running) {
Console.Write("Enter a number or enter 999 to exit: ");
int inputValue;
var inputString = Console.ReadLine();
//Check for "999" which indicates we should display the numbers entered, the total and then exit our loop.
if (inputString == "999") {
//Display the numbers entered
foreach (var number in numbers) {
Console.WriteLine(number);
}
Console.WriteLine("The sum of the values in your array is: " + numbers.Sum());
running = false;
}
else if (Int32.TryParse(inputString, out inputValue) && inputValue > 0) {
//We have valid input, append it to our collection
numbers.Add(inputValue);
}
else {
//The user entered invalid data. Let them know.
Console.WriteLine("Please enter a whole number greater than 0");
}
}
//Loop complete
Console.WriteLine("Press any key to exit.");
Console.ReadLine();
}
You have several small mistakes here.
In your Sum method you are no longer using the array sum1, you're summing the values into sum2, but you're printing sum1. Your sum method should be (as described by Wiktor):
public static void Sum(int[] numbers)
{
int sum2 = 0;
foreach (int i in numbers)
sum2 += i;
Console.WriteLine("The sum of the values in your array is: " + sum2);
}
Also note that you used sum2 =+ i rather than sum2 =+ i. What that's saying is "set sum2 to be equal to the positive value of i" rather than, "add i to sum2.
Next, you have some issues in how you gather your input from the user. First off, arrays don't have a mutable size. The size that they have is fixed when they are created, and the array that you create to hold onto the values to sum up from the users is initialized to a size of 0. (int[] array1 = new int[0];) If you want to get a fixed number of values from the user you can put something other than 0 there for the array size, but based on the context it appears that you want the users to be able to add values until they enter 999 at which point you end. Since you don't know the size before hand you'll want to use a List<int> rather than an array, as you can just add items to it and it will magically grow to support the new items.
I would also suggest making a new method to get all of the values from the user, rather than embedding it in your Main method.
public static List<int> AskUserForNumbers()
{
List<int> numbers = new List<int>();
while(...)//todo determine end condition
{
string userInput = Console.ReadLine();
if(...)//todo determine if user is done
{
}
else
{
int nextNumber = ...;//todo parse user input
numbers.Add(nextNumber);
}
}
return numbers;
}
I'm not sure if it's a requirement for you to stop asking for numbers when the user enters 999 or if that's just what you did. if you have a choice, I would suggest using something different such as a blank line, 0, "quit", "exit", etc. 999 is a number that someone might want to sum.
As mentioned by SPFiredrake, it's best to use int.TryParse() to parse user input, that way if they enter a number that's not an int it won't crash, and you can tell the user that it was no good and they need to try again.