static void Main(string[] args)
{
SortedList<string, double> num2 = new SortedList<string, double>();
string Name;
double Score;
for (int i = 0; i < 1; i++)
{
Console.WriteLine("Name Score:");
Name = Console.ReadLine();
double.TryParse(Console.ReadLine(), out Score);
num2.Add(Name, Score);
}
for (int i = 0; i < 1; i++)
{
Console.WriteLine("Name Score:");
Name = Console.ReadLine();
double.TryParse(Console.ReadLine(), out Score);
num2.Add(Name, Score);
}
for (int i = 0; i < 1; i++)
{
Console.WriteLine("Name Score:");
Name = Console.ReadLine();
double.TryParse(Console.ReadLine(), out Score);
num2.Add(Name, Score);
}
for (int i = 0; i < 1; i++)
{
Console.WriteLine("Name Score:");
Name = Console.ReadLine();
double.TryParse(Console.ReadLine(), out Score);
num2.Add(Name, Score);
}
for (int i = 0; i < 1; i++)
{
Console.WriteLine("Name Score:");
Name = Console.ReadLine();
double.TryParse(Console.ReadLine(), out Score);
num2.Add(Name, Score);
}
Name = "";
foreach (var Score in num2) // error with Score
{
Name += Name + "\t"
+ Score + "\n";
Console.WriteLine(Score);
}
for (int j = 0; j < 1; j++)
{
Console.WriteLine("Name:");
Double Average;
Double Curve;
Average = Score / 5; // wont average.
Curve = 75 - Average;
Console.WriteLine();
}
Console.ReadLine();
}
I am tried to declare the Score and Name for the reader to use at the top before the sort list function.
And I got an error on the line of the comments. Basically, what im trying to do is set the sort list to read 5 scores and Names. Then I use the 5 scores and Names to find the average and Curve. So when I try to do this I get an error. Im also having trouble with the for each loop. How can I fix this program?
Your foreach isn't working because Score is defined as a double already further up in the scope of your Main method (resulting in a syntax error). I'm not sure what you are trying to achieve with that loop - looks like your maybe trying to output each name and the corresponding score for that name in your SortedList:
foreach (var listItem in num2)
{
Console.WriteLine($"Name: {listItem.Key} Score: {listItem.Value}");
}
As for your other problems, you definitely do not need 6 separate for loops. Just make one to read in all of your input:
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Enter a Name");
string name = Console.ReadLine();
Console.WriteLine("Enter a Score");
double score = double.Parse(Console.ReadLine());
num2.Add(name, score);
}
This will ask the user to supply 5 names and 5 scores. Then to get your average and curve, you can do something like:
double average = num2.Sum(item => item.Value) / 5;
double curve = 75 - average;
Console.WriteLine($"Average: {average} Curve: {curve}");
Console.ReadLine();
This uses the Enumerable.Sum
to add together all of your Value's in your Sorted List (you may need to add using System.Linq; to your file. No need to wrap this in another for loop as far as I can tell.
With your code, despite all of your for loops, it should still have captured 5 names and scores. However, when it comes to actually doing something with the values you captured from input, you weren't using them in any way. Ignoring the foreach loop, Score would have been set to whatever the last value entered in your 5th for loop, explaining why your Average wasn't working as expected.
Some other things to note:
If two identical names are supplied, this will error, since you can't have two items with the same Key in a SortedList. You'll want to handle that.
double.TryParse will result in the out parameter being set to 0 if the value attempting to be parsed cannot be. This could cause unexpected results with your average and curve later on. I switched it to use just double.Parse instead, which will throw an error if it cannot parse the value. You could account for this by doing something like this:
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Enter a Name");
string name = Console.ReadLine();
Console.WriteLine("Enter a Score");
double score;
bool isScoreValid = double.TryParse(Console.ReadLine(), out score);
while (!isScoreValid)
{
Console.WriteLine("Invalid score. Please enter a new one");
isScoreValid = double.TryParse(Console.ReadLine(), out score);
}
num2.Add(name, score);
}
Related
In one of my classes I was given an assignment to write a simple program that combines multiple numbers entered from the console, but only adding up the even ones. I was able to do the summing up part pretty easily but I can't figure out how to check for even numbers! If anyone can figure out how or explain for a beginner how to do it would be greatly appreciated.
Here's the full code so far:
using System;
namespace Test_3
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Amount of numbers n = ");
var n = int.Parse(Console.ReadLine());
Console.WriteLine("Enter numbers:");
var sum = 0;
for (int i = 0; i < n; i++)
{
if (sum%2 == 0)
{
}
else
{
}
var num = int.Parse(Console.ReadLine());
sum = sum + num;
}
Console.WriteLine("The sum of the numbers is " + sum);
}
}
}
You seem to already know how to get the even numbers but here is how to apply it!
Console.WriteLine("Amount of numbers n = ");
var n = int.Parse(Console.ReadLine());
Console.WriteLine("Enter numbers:");
var sum = 0;
for (int i = 0; i < n; i++)
{
var num = int.Parse(Console.ReadLine()); //first read a number from the console
if (num % 2 == 0) //then check if it is even
{
sum = sum + num; //if it is, then add it to sum
}
}
Console.WriteLine("The sum of the numbers is " + sum);
You seem not to get the idea of an if-clause, let me explain this, using the following pieces of code:
Your code:
for (int i = 0; i < n; i++)
{
if (sum%2 == 0)
{
}
else
{
}
var num = int.Parse(Console.ReadLine());
sum = sum + num;
}
This calculates the sum of all numbers (you check whether a number is even or not, but you don't use that information).
My proposal: (you check if a number is even, and you use that information)
for (int i = 0; i < n; i++)
{
if (sum%2 == 0)
{
var num = int.Parse(Console.ReadLine());
sum = sum + num;
}
else
{
}
}
Another one, how to calculate the sum of the odd numbers? (Here you check if a number is even, but you use the case where it is not)
for (int i = 0; i < n; i++)
{
if (sum%2 == 0)
{
}
else
{
var num = int.Parse(Console.ReadLine());
sum = sum + num;
}
}
So, you see? You can use if-clauses to filter out what you want to do when a condition is met or when a condition is not met, that's the whole idea behind it.
You need to check whether the variable num is divisible by two instead of the sum. The code you have checks if the sum is even and if so does nothing since you didn't add anything to the if statement. Instead, you should be doing if ( num % 2 == 0) .
You also need to move where num is declared to the top of the for loop and move the part where you add to the sum to the inside of the conditional (The if statement).
I´m still very new to C#, we are supposed to use for-loops not methods. My question is how to limit values (1 to 25) that users puts in.
"The game" is supposed to ask a user to put in his values then it throw´s a random number and checks if it´s among numbers kept in myArray.
{
int[] myArray = new int[10];
Console.WriteLine("Write down your numbers");
for (int i = 0; i < 10; i++)
{
Console.WriteLine("Type in values for index nr {0}: ", i);
//user is asked to put in 10 values, what I need to do is to limit and
save as elements values in range between 1 and 25, so the loop continues (i++), if user types in a number that is outside that range my loop supposed to go a step back as if (i--)
myArray[i] = int.Parse(Console.ReadLine());
}
var rand = new Random(); //a random number is thrown
int rand1 = Convert.ToInt32(rand.Next(0, 25)); //random number ranges between 0 and 25
Console.WriteLine("{0}", rand1);
for (int i = 0; i < tal.Length; i++) //checking if random number is among users inputs
{
if (tal[i] == rand1)
{
Console.WriteLine("The random number {0} is among
your values", rand1);
}
else
{
Console.WriteLine("Random number isn´t among your
numbers");
break;
}
}
for (int i = 0; i < 10; i++)
{
Console.WriteLine("Type in values for index nr {0}: ", i);
if (int.TryParse(Console.ReadLine(), out int result) && result >= 0 && result <= 25)
{
myArray[i] = result;
}
else
{
i--;
Console.WriteLine("Wrong number!");
}
}
Your issue is that you try to maintain an index i that indicate your current position in the array.
One of the solution will be to simply drop it and add item to a collection till you have 10 items.
Here I took a HashSet<int> because we can't have duplicate in HashSet.
Any time you try to add one, it will simply drop it. But If you want to allow duplicate you can use a simple List<int>.
int collectionSize = 10;
int lowerBound = 1, upperBound = 25;
var userSelectedNumbers = new HashSet<int>();
while (userSelectedNumbers.Count() < collectionSize)
{
Console.WriteLine($"Enter an int between {lowerBound} and {upperBound} : ");
var input = Console.ReadLine();
if (int.TryParse(input, out int value)
&& lowerBound <= value
&& value < upperBound
)
{
userSelectedNumbers.Add(value);
}
else {
Console.WriteLine("Not a valid input!");
}
}
Console.Clear();
Console.WriteLine(
$"userSelectedNumbers contains {userSelectedNumbers.Count()} elements : {"
+ string.Join(", ", userSelectedNumbers) + "}"
);
You can then validate if the random numer is within the range using Contains :
var random = new Random();
int computerPick = random.Next(0, 25);
Console.WriteLine("Computer picked : " + computerPick);
if (userSelectedNumbers.Contains(computerPick))
{
Console.WriteLine("You win!");
}
else {
Console.WriteLine("You loose!");
}
Don't forget the using :
using System.Collections.Generic;
using System.Linq;
nb: The range is define using 1 ≤ x < 25, using W. Dijkstra convention http://www.cs.utexas.edu/users/EWD/ewd08xx/EWD831.PDF
I need to write a console app that asks the user how many number (double) to enter. After accepting that many numbers, display every other number entered. There always seems to be an error when I try to use a double. I also get this error "System.IndexOutOfRangeException was unhandled
HResult=-2146233080
Message=Index was outside the bounds of the array."
after the the for loop has gone through the last loop for this line
myArrai1[i] = int.Parse(Console.ReadLine());
in the first for loop
this all the code I have been able to try to brainstorm with.
class Program
{
static void Main(string[] args)
{
Console.Write("Enter Item Count: ");
int number = int.Parse(Console.ReadLine());
int[] myArrai1 = new int[number];
int i = 0;
for (i = 1; i <= number; i++)
{
Console.WriteLine("Enter Number " + i.ToString() + ": ");
myArrai1[i] = int.Parse(Console.ReadLine());
}
for (i = 0; i < number; i++)
{
Console.WriteLine("Every other number entered: ");
Console.WriteLine(myArrai1[i += 2]);
}
Console.ReadLine();
}
}
}
Not too far off, main changes to fix fix this was loop#1 was set to 0 index to prevent out of range and loop#2 was simplified by intervaling at 2 of ++.
The rest of the changes were aesthetic; I changed the input Console.WriteLine to just Console.Write to keep the input on the same line, and moved the Every Other Line statement to precede the output display loop instead of being written on every iteration.
Console.Write("Enter Item Count: ");
int number = int.Parse(Console.ReadLine());
int[] myArrai1 = new int[number];
for (int i = 0; i < number; i++) {
Console.Write("Enter Number " + (i + 1) + ": ");
myArrai1[i] = int.Parse(Console.ReadLine());
}
Console.WriteLine("Every other number entered: ");
for (int j = 0; j < number; j = j + 2) {
Console.WriteLine(myArrai1[j]);
}
What calculations do I need to find the total?
else if (a =2) {
TotalCredit = new int[15];
Console.WriteLine("please enter the credits");
int i = 0;
for (i = 0; i < 15; i++) {
int Credit = Convert.ToInt32(Console.ReadLine());
Total + Credit;
}
Console.WriteLine(Total);
}
You need to declare the variable Total ahead it use and it should be before loop to keep its scope available after loop. More than that your sum operation should be corrected using += operator
Correct it as follows:
int Total=0;
for (i = 0; i < 15; i++)
{
int Credit = Convert.ToInt32(Console.ReadLine());
Total += Credit;
}
Console.WriteLine(Total);
Try this.
else if (a ==2)
{
int[] TotalCredit = new int[15];
Console.WriteLine("please enter the credits");
int i = 0;
int Total = 0;
for (i = 0; i < 15; i++)
{
int Credit = Convert.ToInt32(Console.ReadLine());
Total += Credit;
}
Console.WriteLine(Total);
}
I've added this line int Total = 0; to declare a variable Total with the value 0, to store the total there.
Then I've changed a line in the for to be Total += Credit; which is the same as Total = Total + Credit; so every new value will be added and store into the variable Total.
This is a C# I guess, as convention https://msdn.microsoft.com/en-us/library/ff926074.aspx you'd better declare the variables to be lowercase.
As you have declared an array of ints I'm going to assume you want to keep the actual values the user has entered and not just the total. Make sure you add System.Linq in your using clauses.
else if (a==2)
{
var totalCredit = new int[15];
Console.WriteLine("please enter the credits");
for (int i = 0; i < 15; i++)
totalCredit[i] = Convert.ToInt32(Console.ReadLine());
var total = totalCredit.Sum();
Console.WriteLine (total);
}
A good idea would be to validate input gracefully, and minimize duplication of the magic constant 15—even better would be to assign it a meaningful name (the same goes for the a variable). Also, if you intend to store each input into the array for later usage outside of the else if block, you'll need to declare it outside of said block. However, if you do not need the individual credit values, the array is unnecessary.
const int numberOfCredits = 15;
int[] credits = new int[numberOfCredits];
...
else if (a == 2)
{
int total = 0;
int count = 0;
while (count < numberOfCredits)
{
Console.WriteLine("Enter credit #" + (count + 1).ToString() + ":");
int input;
if (int.TryParse(Console.ReadLine(), out input))
{
credits[count] = input;
total += input;
count += 1;
}
}
Console.WriteLine(total);
}
So the code for the function (Named InsertMark) is below. How would you call this function to enter the marks for say 10 people into an array called iMarks?
static void InsertMark(int [] piMarkArray, int piStuNum)
{
int iMark;
Console.Write("Enter mark for student " + piStuNum + ": ");
iMark = Convert.ToInt32(Console.ReadLine());
while (iMark < 0 || iMark > 100)
{
Console.Write("Not a percentage. Enter again: ");
iMark = Convert.ToInt32(Console.ReadLine());
}
//update array element with this mark
piMarkArray[piStuNum] = iMark;
}
Thanks.
Just move the line piMarkArray[piStuNum] = iMark; inside while loop, use index, and exit the loop if index is not less than array length.
int index=0;
while ((iMark < 0 || iMark > 100) && index < piMarkArray.Length) // exit the loop array is full
{
Console.Write("Not a percentage. Enter again: ");
iMark = Convert.ToInt32(Console.ReadLine());
piMarkArray[index++] = iMark; // Here marks are set
}
//update array element with this mark
Here you create array which will hold 10 marks and fill it with your method in a loop:
int[] marks = new int[10];
for(int i = 0; i < marks.Length; i++)
InsertMark(marks, i);
In main function you could have a code:
int iMarks[10];
for(int i = 0; i <10; i++ )
InsertMark(iMarks, i)
are you looking for something like this?
for(int i=0; i<10; i++)
{
InsertMark(iMarks, i);
}
You need to declare an array of size 10: int[] iMarks = new int[10], then in a for loop pass the array and the counter value through to the function.
int[] iMarks = new int[10];
for(int x = 0; x < 10; x++)
InsertMark(iMarks, x);
Here is the full class/ working example:
static void Main(string[] args)
{
int[] iMarks = new int[10];
for(int x = 0; x < 10; x++)
InsertMark(iMarks, x);
Console.Read();
}
static void InsertMark(int[] piMarkArray, int piStuNum)
{
int iMark;
Console.Write("Enter mark for student " + piStuNum + ": ");
iMark = Convert.ToInt32(Console.ReadLine());
while(iMark < 0 || iMark > 100)
{
Console.Write("Not a percentage. Enter again: ");
iMark = Convert.ToInt32(Console.ReadLine());
}
//update array element with this mark
piMarkArray[piStuNum] = iMark;
}
}
There are always multiple ways to code anything, and this is no exception. What I'm putting here is one example of idiomatic C# to do this. There are at least two variants I can think of which would be better, but this keeps the closest to the original idea.
First, a basic Student class:
class Student
{
public int ID;
public int Mark;
}
Then, a function to prompt for the mark
int GetMark(int studentID)
{
Console.Write("Enter mark for student " + studentID + ": ");
int mark = Convert.ToInt32(Console.ReadLine());
while (iMark < 0 || iMark > 100)
{
Console.Write("Not a percentage. Enter again: ");
iMark = Convert.ToInt32(Console.ReadLine());
}
return mark;
}
Finally, from your main program, you have a list or array of Student objects called AllStudents and you do:
foreach (Student student in AllStudents)
{
student.Mark = GetMark(student.ID);
}
Alternatively, if you aren't using classes, your loop could be:
int[] marks = new int[10]; // Or whatever size it needs to be.
for (int i = 0; i < marks.Length; i++)
{
marks[i] = GetMark(i);
}