Error Reading User Input into Array - c#

So I'm intentionally overcomplicating a homework assignment I was given because I was bored and wanted to learn more about c#. The original assignment is as follows:
"Compute the average of five exam scores ranging between 50 and 90. Declare and perform a compile-time initialization with the five values. Use a constant to define the number of scores. Display all scores and the average value formatted with no digits to the right of the decimal."
So I decided rather than just putting the 5 scores in, I'd allow the user to input them into an array and then calculate it from that.
Console.WriteLine("Enter 5 test scores between 50 and 90:");
int i = 0;
double total = 0;
double[] Scores;
Scores = new double[5];
while (i < 5)
{
Console.WriteLine("Input Score " + (i + 1) + ":");
String input = Console.ReadLine();
Scores[i] = double.Parse(input);
total += Scores[i];
i++;
}
Console.WriteLine("The average of the scores is: " + (total/5));
The issue is that the Scores[i] = double.Parse(input); is throwing an error saying that the input is in the wrong format. So the program won't even run to let me put IN an input, but it says the input format is incorrect.
Any suggestions? I'm probably missing something obvious.
EDIT: Ok, so what ended up working was changing the code to
Console.WriteLine("Input Score " + (i + 1) + ":");
Scores[i] = double.Parse(Console.ReadLine());
total += Scores[i];
i++;
Not sure what it actually changed but it seems to work pretty flawlessly!

Related

How to build a loop that allows a user to input positive and whole numbers and ends when 0 or negative numbers are input

Hello good people.
So I am struggling a little with the while/for/do while loops as I am having trouble understanding their structure.
And that causes me to have some issues with my homework assignment , what I need to do is a write a code for the following:
I need a program that allows a user to input only positive and whole numbers , the program also calculates their sum and shows the result for each input in the console ( for example the user inputs 1 and than 2 and than 3 and than 4 the program will show the result as 10).
The program will end if the user has input 0 or a negative number.
I can only use for / while / do while.
My experience is really with only the basic stuff like int , double , loop , string , etc'
I can't really wrap my head around it very much and I would love to get some ideas and assistance.
I've tried but got stuck at the beginning has I have no idea how to start with it
edit:
I've really just dabbled with the idea because I have no idea how to start , I've made this, it was no good
int number, i=1 , min;
Console.WriteLine("Please enter only positive WHOLE numbers to calculate");
number = int.Parse(Console.ReadLine());
while (i <= number)
{
Console.WriteLine("This is the smallest number: " + number);
i++;
}
edit: I did this, but I wonder if there's a better way
int number, sum = 0;
Console.WriteLine("Please enter only positive WHOLE numbers to calculate");
start:
number = int.Parse(Console.ReadLine());
while (number > 0)
{
Console.WriteLine("This is your number : " + number);
sum += number;
Console.WriteLine("The sum is: " + sum);
goto start;
}
while (number <= 0)
{
Console.WriteLine("Please enter a number bigger than 0");
break;
}
Loops are for code that repeats. In your task, input and addition repeat, so put them in loop. while and for loops check the condition before executing loop body, and do checks after.
Your algorithm is like that:
Read input.
Check if it's positive, if it's not, exit.
Add it to sum.
Repeat.
So you should check the condition in the midst of loop. You can use break to exit loop early. Since you neither check condition in beginning nor end, just write an infinite loop.
int n, sum = 0;
while (true) {
n = int.Parse (Console.ReadLine ());
if (n <= 0) break;
sum += n;
}
Updated. Yes you can shorten your code.
int number, sum = 0;
Console.WriteLine("Please enter only positive WHOLE numbers to calculate");
start:
number = int.Parse(Console.ReadLine());
You put a repeating statement outside of loop. It forced you to use a label. Labels can easily make your logic very difficult to read.
while (number > 0)
{
Console.WriteLine("This is your number : " + number);
sum += number;
Console.WriteLine("The sum is: " + sum);
goto start;
You exit the loop indefitinely, so that's no difference between while and if here.
}
while (number <= 0)
{
Console.WriteLine("Please enter a number bigger than 0");
break;
And the same again.
}
Remember to use loop when something repeats and don't use when nothing does.
Console.WriteLine ("Please enter only positive WHOLE numbers to calculate");
int n, sum = 0;
while (true) {
n = int.Parse (Console.ReadLine ());
Console.WriteLine ("This is your number : " + number);
if (n <= 0) {
Console.WriteLine("Please enter a number bigger than 0");
// actually he won't get a chance to enter it. Why to ask him then?
break;
}
sum += n;
Console.WriteLine("The sum is: " + sum);
}
1 way of doing it:
int number, i=0 , min=1; // min is the minimum value, i is the sum, number is the input you give
while (i <= min)// checks if its lesser than zero
{
Console.WriteLine("Please enter only positive WHOLE numbers to calculate");
number = int.Parse(Console.ReadLine());
i += number;
Console.WriteLine("This is the sum: " + i);
}
Other way of doing it:
int number, i=0 , min=1; // min is the minimum value, i is the sum, number is the input you give
while (true)
{
Console.WriteLine("Please enter only positive WHOLE numbers to calculate");
number = int.Parse(Console.ReadLine());
if(i<=min)
break;
i += number;
Console.WriteLine("This is the sum: " + i);
}
I think the best thing to do is read the documentation:
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/while
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/do

Displaying several integers in one label

I need some clarification. I'm doing a lab project that wants me to gather 5 numbers, then when a button is clicked it adds them, divides them into dozens, and also tells the remainder. here's a portion of my code, I'm wanting to know if there's something I'm missing in the line with label2?
int sum = num1 + num2 + num3 + num4 + num5;
int dozen = sum / 12;
int remainder = sum % 12;
label2.Text = "The total is {0}. That's {1} dozen with {2} remainders",sum , dozen, remainder;
}
}
}
any help would be appreciated.
Yes, you're missing a call to string.format or nowadays you can do:
label2.Text = $"The total is {sum}. That's {dozen} dozen with {remainder} remainders";
Change to this:
label2.Text = String.Format("The total is {0}. That's {1} dozen with {2} remainders",sum , dozen, remainder);
String.Format take arguments.

How do I calculate a for loop to display in a listbox where the first loop is user input but the remaining iterations are calculated?

I am trying to create a loop that will calculate inside a listbox but run the actual calculation after the first statement and compound the remaining...
Here is my code:
// Count Loop
int numdays;
numdays = 1;
// Declare and Assign Variables
double organism, daysmultiply, dailyincrease;
organism = double.Parse(OrganismTextBox.Text);
dailyincrease = double.Parse(DailyIncreaseTextBox.Text);
daysmultiply = double.Parse(DaysMultiplyTextBox.Text);
ResultsListBox.Items.Clear();
// Need to have daily increase texbox formatted as a percentage - unsure how
for (numdays = 0; numdays <= daysmultiply; numdays++)
{
ResultsListBox.Items.Add(" Day " + numdays + " Popualtion is " + (organism * dailyincrease));
numdays = numdays++;
}
The result of the calculation is a loop that calculates .6 each time it iterates. I am trying to figure out how to compound the loop each time.
Can someone please help?
Your values don't "compound", because you do nothing in the loop that would cause that to happen, i.e. to change the values of the variables involved in calculating your values.
Your loop has other issues as well: you increment the loop index twice for each iteration; and you unnecessarily reassign the result of the post-increment operator back to the variable (the whole point of the operator is to do that assignment implicitly).
You probably want a loop that looks more like this:
for (numdays = 0; numdays <= daysmultiply; numdays++)
{
ResultsListBox.Items.Add(" Day " + numdays + " Population is " + organism);
organism = organism * dailyincrease;
}
or possibly:
for (numdays = 0; numdays <= daysmultiply; numdays++)
{
ResultsListBox.Items.Add(" Day " + numdays + " Population is " + organism);
organism += organism * dailyincrease;
}
The first example simply multiplies the organism value by the dailyincrease value. The second example does that multiplication and then adds the result to the current organism value. It's not clear from your question which is appropriate; it would depend on what the actual meaning of dailyincrease is. That is, if it's strictly the scale applied each day, then the first example is correct. If it's a representation of the percentage change (e.g. the 0.6 to which you refer means that the population increases 60% each day), then the second example is correct.

For Loop C#-- Adding

How to find a loop that will successfully add 5 numbers. Here is the homework question.
Add a loop that will take a number input by the user and add it to a running total (the ReadLine() method will get a string from the user).
You’ll notice in the above code there are two variables declared.
One is total of the double data type which will have the total of the 5 entered numbers.
The other is a temp string variable to take the user input, convert to double, and then add the converted value to the total.
Using what you have learned in case 2 about taking input and converting to an int32, take the input and convert ToDouble() instead of int32.
total = total + Convert.ToDouble(temp);
case "3":
double total = 0;
string temp = "0";
Console.WriteLine("Enter 5 numbers here for addition \n");
for (total = 0; total <= 6; total++);
{
Console.WriteLine(total + "" + temp);
total = total + Convert.ToDouble(temp);
}
break;
When I tried entering this in, the debugging program exited out and gave me a set number.
It keeps saying that string will not convert to integer when I tried entering string as an expressions instead.
Here is the result I am trying to get.
1
2
3
4
5
Total:15 This is the answer I am trying to get.
You set temp to be an empty string and then it never becomes a number, hence you can't cast it to a double....
Convert.ToDouble(input) won't do anything either as you need to store the value, i.e.
double result = Convert.ToDouble (input)
The loop is wrong because you only ever take one input - you need to put your Console.ReadLine in your loop and then append what the user inputs to your total.
you probably need to do:
int index=Convert.ToDouble(input);
and use in the for loop something like
for(int i=0;i<index;i++)
since as it stands you retrieve an input but don't use it, in for loop in fact you're trying to set it to zero -> for(input=0;....)
which can't be done since input is a string and not a number
in case 3 you're using total as an index and as the total variable in the calculation you can't do that
you need another variable to use as a index:
for (int i = 0; i<= 6; i++);
{
Console.WriteLine(total + "" + temp);
total = total + Convert.ToDouble(temp);
}
Console.Write("Enter how many numbers you want to enter and sum up: ");
double n = double.Parse(Console.ReadLine());
double r;
double sum = 0;
for (int i = 0; i < n; i++)
{
Console.Write("{0} Enter number ", i);
r = double.Parse(Console.ReadLine());
sum += r;
Console.WriteLine(sum);
}

Comparing in Array

There is something wrong with my code. I am teaching myself c# and one of the challenges in this chapter was to prompt the user for 10 numbers, store them in an array, than ask for 1 additional number. Then the program would say whether the additional number matched one of the numbers in the array. Now what I have below does work, but only if I enter in a comparison number that is less than 10 which is the size of the array.
I'm not sure how to fix it. I am not sure how to do the comparison. I tried a FOR loop first which kind of worked, but ran through the loop and displayed the comparison against all 10 numbers so you would get 9 lines of No! and 1 line of Yes!. I put in a break; which stopped it counting all 10 but if I entered the number 5 for comparison, then I would get 4 lines of No! and 1 of Yes!. The below has been the only way I could get it to work reliably but only as long as the number isn't out of the bounds of the array.
I can see why I get the error when the number is above 10, I just don't know what to use to compare it but still allow the user to enter in any valid integer. Any assistance would be great!
int[] myNum = new int[10];
Console.WriteLine("Starting program ...");
Console.WriteLine("Please enter 10 numbers.");
for (int i = 0; i <= 9; ++i)
{
Console.Write("Number {0}: ", i + 1);
myNum[i] = Int32.Parse(Console.ReadLine());
}
Console.WriteLine("Thank you. You entered the numbers ");
foreach (int i in myNum)
{
Console.Write("{0} ", i);
}
Console.WriteLine("");
Console.Write("Please enter 1 additional number: ");
int myChoice = Int32.Parse(Console.ReadLine());
Console.WriteLine("Thank you. You entered the number {0}.", myChoice);
int compareArray = myNum[myChoice - 1];
if (compareArray == myChoice)
{
Console.WriteLine("Yes! The number {0} is equal to one of the numbers you previously entered.", myChoice);
}
else
{
Console.WriteLine("No! The number {0} is not equal to any of the entered numbers.", myChoice);
}
Console.WriteLine("End program ...");
Console.ReadLine();
You were on the right track- you want to loop through the array in myNum and compare each element to the variable myChoice. If you don't want to print whether each element of the array is a match, create a new variable and use it to keep track of whether you've found a match or not. Then after the loop you can check that variable and print your finding. You'd usually use a bool variable for that- set it false to start, then true when you find a match.
bool foundMatch = false;
for (int i = 0; i < 10; i++) {
if (myNum[i] == myChoice) {
foundMatch = true;
}
}
if (foundMatch) {
Console.WriteLine("Yes! The number {0} is equal to one of the numbers you previously entered.", myChoice);
}
If you include the System.Linq namespace (or if you change the type of myNum to be something that implements ICollection<T>, like List<T>), you can use myNum.Contains(myChoice) to see if the value myChoice matches one of the values in myNum. array.Contains returns a boolean that is true if the specified value is found in the array and false if it is not.
You can update your code to use this like so:
//int compareArray = myNum[myChoice - 1]; // This line is no longer needed
if (myNum.Contains(myChoice))
{
Console.WriteLine("Yes! The number {0} is equal to one of the numbers you previously entered.", myChoice);
}
else
{
Console.WriteLine("No! The number {0} is not equal to any of the entered numbers.", myChoice);
}
If you're looking for numbers that are definitely between 1 and 10, then before you use
int compareArray = myNum[myChoice - 1];
check if it's over the value of 10. For example:
while(myChoice > 10)
{
Console.Write("Please choose a number less than or equal to 10: ");
myChoice = Int32.Parse(Console.ReadLine());
}
The benefit of putting it inside a while loop instead of an if tag means that, when the user enters another number, the value of myChoice will be rewritten, and compared against. If they enter a number over 10, it'll keep responding Please choose a number less than or equal to 10. until the number they input is below or equal to 10:` Then, your program will continue.
However, if you want to compare it against the array, rather than put in a fixed number comparison, consider the following while loop:
while(myChoice > myNum.Length)
{
Console.Write("Please choose a number less than or equal to {0}: ", myNum.Length);
myChoice = Int32.Parse(Console.ReadLine());
}
This will work for any sized array then, without you having to change the while loops content. By using this system, you can then ensure that you won't get an IndexOutOfBounds exception, so long as you subtract 1 when using it as an index.
You are looking to compare a final, 11th value and trying to determine if its in an array of 10 previous entries?
Try:
for(int i = 0; i < array.length - 1; i++;)
{
If(array[i] == input)
return true;
}
return false;
You should be able to figure out how to implement this completely yourself, as you did want to do it as an exercise.
Edit: If someone wants to check this or complete it in correct syntax, go ahead. I posted this rough outline from a phone.

Categories