How do I make 2 column list - c#

So currently I have an assignment where I input the students names and grades and create a 2 column list where each name is paired with a grade. Currently I am having issues creating the list it only prints out one of the students and one of the grades. I created an array with a size of 26, but only used 5 just to test it out and save time.
Here is the code
static void Main(string[] args)
{
Console.WriteLine("Welcome to the grade book input the student and grades \n");
string[] students = new string[26];
string names = "";
int grd = 0;
Console.WriteLine("Names \t\t Grades");
for (int inc = 1; inc <= 26; inc+=2)
{
Console.WriteLine("Please enter the names");
for (int x = 1; x <= 5; x++)
{
names = Console.ReadLine();
students[x] = names;
}
Console.WriteLine("Please enter the grades");
bool valid;
for (int scr = 1; scr <= 5; scr++)
{
do
{
valid = int.TryParse(Console.ReadLine(), out grd);
if (!valid || grd > 100 || grd < 0)
Console.WriteLine("Please enter a grade between 0-100");
else
Console.WriteLine("Your grade is {0}", grd);
} while (!valid || grd > 100 || grd < 0);
}
Console.WriteLine(names + "\t\t {0}", grd);
}

To print everything you need to loop through the names and grades arrays as shown below. You should also utilize index 0 of the arrays otherwise you will run into an issue when you try to put the 26th item in them.
Console.WriteLine("Welcome to the grade book input the student and grades \n");
string[] students = new string[26];
int[] grades = new int[26]; // make an array for the grades
string names = "";
int grd = 0;
Console.WriteLine("Names \t\t Grades");
Console.WriteLine("Please enter the names");
for (int x = 0; x < 5; x++) // start at index 0 and go to index 4, arrays start with index 0
{
names = Console.ReadLine();
students[x] = names;
}
Console.WriteLine("Please enter the grades");
bool valid;
for (int scr = 0; scr < 5; scr++)
{
do
{
valid = int.TryParse(Console.ReadLine(), out grd);
if (!valid || grd > 100 || grd < 0)
Console.WriteLine("Please enter a grade between 0-100");
else
Console.WriteLine("Your grade is {0}", grd);
} while (!valid || grd > 100 || grd < 0);
grades[src] = grd; // save the valid grade in the grades array
}
// to print the names and grades you must loop through each index of the array
for (int i = 0; i < 5; i++)
{
// EDIT: need to access the students array here
Console.WriteLine("{0}\t\t{1}", students[i], grades[i]);
}

Related

Comparison of grades of students and Coins distributions

I'm stuck at this. I`m beginner into software development. You get a list of N students and then a list of ratings for each student. A student which has bigger rating than his neighbour from list gets more coins than both of them. For example:
Data input:
3
John
Dan
Sam
9
10
8
Data output:
John 1
Dan 3
Sam 1
My output is just the names of the students.
I wrote this code:
using System;
class Program
{
private static void Main(string[] args)
{
int n = Convert.ToInt32(Console.ReadLine());
var numberCoins = new int[n];
string[] studentNames = new string[n];
numberCoins[0] = 1;
for (int i = 0; i < n; i++)
{
studentNames[i] = Console.ReadLine();
}
int[] grades = new int[n];
for (int i = 0; i < n; i++)
{
grades[i] = Convert.ToInt32(Console.ReadLine());
}
for (int i = 1; i < n; i++)
{
if (grades[i] > grades[i - 1])
{
numberCoins[i] = numberCoins[i - 1] + 1;
}
}
for (int i = n - 2; i >= 0; i--)
{
if (grades[i] > grades[i + 1])
{
numberCoins[i] = numberCoins[i + 1] + 1;
}
}
for (int i = 0; i < n; i++)
{
Console.WriteLine(studentNames[i], " ", numberCoins[i]);
}
Console.ReadLine();
}
}
You didn't mention if there is any pattern to give coins to the students. And if we have specific number of coins or not.
If we consider at first no one has any coins the result must be something like the following:
Please specify the number of the students:
3
Please write students' name (after each name hit the ENTER):
John
Dan
Sam
Please write students' ratings (after each rating hit the ENTER):
9
10
8
The result:
John: 0
Dan: 2
Sam: 0
I wrote a piece of code which might help you approach the functionality you want.
using System;
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Please specify the number of the students:");
int n = int.Parse(Console.ReadLine());
string[] studentNames = new string[n];
int[] studentRatings = new int[n];
int[] studentCoins = new int[n];
Console.WriteLine();
Console.WriteLine("Please write students' name (after each name hit the ENTER):");
for (int i = 0; i < n; i++)
{
studentNames[i] = Console.ReadLine() ?? string.Empty;
}
Console.WriteLine();
Console.WriteLine("Please write students' ratings (after each rating hit the ENTER):");
for (int i = 0; i < n; i++)
{
studentRatings[i] = int.Parse(Console.ReadLine());
}
Console.WriteLine();
Console.WriteLine("The result:");
for (int i = 0; i < n; i++)
{
int coins = 1;
studentCoins[i] = 0;
if (i != 0)
if (studentRatings[i] > studentRatings[i - 1])
coins++;
if (i != n - 1)
if (studentRatings[i] > studentRatings[i + 1])
coins++;
studentCoins[i] = coins;
}
for (int i = 0; i < n; i++)
{
Console.WriteLine($"{studentNames[i]}: {studentCoins[i]}");
}
}
}

C# incorrect output

This is my code, its purpose it to enter number of students, then ask each student for their name and each student enters 5 marks... My problem is that when I run the code, for example, if I enter 2 students , it asks for their name but then asks for their mark 10 times instead of 5. So it is outputting the total times to enter the mark instead of the 5 for each student, how do I fix this?
int total = 0;
int gt50Count = 0;
Console.WriteLine("How many students are there?");
int students = int.Parse(Console.ReadLine());
for (int y = 1; y <= students; y++)
{
Console.WriteLine("Enter student name");
string name = Console.ReadLine();
for (int ask = 1; ask <= students; ask++)
{
for (int x = 1; x <= 5; x++)
{
Console.WriteLine("Enter your mark");
int mark = int.Parse(Console.ReadLine());
if (mark > 100 || mark < 0)
{
Console.WriteLine("Invalid mark,Enter your mark again");
int newmark = int.Parse(Console.ReadLine());
mark = newmark;
}
total += mark;
if (mark >= 50)
{
gt50Count++;
}
}
}
}
Console.WriteLine("sum = " + total);
double average = (total / 5) * 1.00;
Console.WriteLine("average = " + average);
Console.WriteLine("Greather or equal to 50 count = " + gt50Count);
Console.ReadLine();
}
}
}
You have nested loop over student, once again.
for (int ask = 1; ask <= students; ask++) //why this loop ?
{
..
for (int x = 1; x <= 5; x++) // 2 x 5 = 10
{
.... //ask for mark 10 times
}
}
You had an extra for loop in there that simply needed to be removed. Also, I'm assuming you're wanting to get the sum and average for each student entered. To do that, you'll need to include that functionality at the bottom of your first for loop. Check out this refactored code:
int total = 0;
int gt50Count = 0;
Console.WriteLine("How many students are there?");
int students = int.Parse(Console.ReadLine());
for (int y = 1; y <= students; y++)
{
Console.WriteLine("Enter student name");
string name = Console.ReadLine();
for (int x = 1; x <= 5; x++)
{
Console.WriteLine("Enter your mark");
int mark = int.Parse(Console.ReadLine());
if (mark > 100 || mark < 0)
{
Console.WriteLine("Invalid mark,Enter your mark again");
int newmark = int.Parse(Console.ReadLine());
mark = newmark;
}
total += mark;
if (mark >= 50)
{
gt50Count++;
}
}
Console.WriteLine("sum = " + total);
double average = (total / 5) * 1.00;
Console.WriteLine("average = " + average);
Console.WriteLine("Greather or equal to 50 count = " + gt50Count);
Console.ReadLine();
}

do/while and if/else problems

I have to put in an extra "test score" to get an answer.
(i.e i have to enter six 5' to get 25)
I can't get the do/while & if statements to loop if there is more than one number outside the "while" range. I haven't been coding for very long, a couple weeks so try and break down the answers. Thanks for the help!
Here is my code
Console.Write("Enter the number of tests: ");
int n = int.Parse(Console.ReadLine());
int[] scores = new int[n];
Console.WriteLine("----------------------------------------");
Console.WriteLine("Please enter the test scores");
int i;
do
{
i = Convert.ToInt32(Console.ReadLine());
if (i < 0)
{
Console.WriteLine("Please enter a value greater than 0");
}
if (i > 100)
{
Console.WriteLine("Please enter a value less than 100");
}
} while (i < 0 || i > 100);
for (i = 0; i < n; i++)
{
scores[i] = int.Parse(Console.ReadLine());
}
int sum = 0;
foreach (int d in scores)
{
sum += d;
}
Console.WriteLine("The sum of all the scores is {0}",sum);
Console.ReadLine();
Put the do block that does the input validation inside the for loop:
Console.Write("Enter the number of tests: ");
int n = int.Parse(Console.ReadLine());
int[] scores = new int[n];
Console.WriteLine("----------------------------------------");
Console.WriteLine("Please enter the test scores");
for (int i = 0; i < n; i++)
{
int input = -1;
do
{
input = Convert.ToInt32(Console.ReadLine());
if (input < 0)
{
Console.WriteLine("Please enter a value greater than 0");
}
else if (input > 100)
{
Console.WriteLine("Please enter a value less than 100");
}
} while (input < 0 || input > 100);
scores[i] = input;
}
int sum = 0;
foreach (int d in scores)
{
sum += d;
}
Console.WriteLine("The sum of all the scores is {0}", sum);
Console.ReadLine();
n is the number of tests, meaning the amount of scores counter i should be the same as the amount of tests. Also prefer Convert.ToInt32 to int.Parse since it throws exceptions in case it isn't able to make the conversion.
Console.Write("Enter the number of tests: ");
int n = Convert.ToInt32(Console.ReadLine());
int sum = 0, i = 0, score = 0;
int[] scores = new int[n];
Console.WriteLine("----------------------------------------");
do {
Console.WriteLine("Please enter the test score #" + (i + 1));
score = Convert.ToInt32(Console.ReadLine());
if (score < 0) {
Console.WriteLine("Please enter a value greater or equal to 0");
}
else if (score > 100)
{
Console.WriteLine("Please enter a value less or equal to 100");
}
else {
scores[i] = score;
i++;
}
} while (i < n);
foreach (int d in scores) {
sum += d;
}
Console.WriteLine("The sum of all the scores is {0}", sum);
Console.ReadLine();
Just for the potential learning opportunity, and and not as a direct answer to your question, here is the way I would do this exercise:
Console.Write("Enter the number of tests: ");
int n = int.Parse(Console.ReadLine());
Console.WriteLine("----------------------------------------");
Console.WriteLine("Please enter the test scores");
int AskForInteger()
{
while (true)
{
if (int.TryParse(Console.ReadLine(), out int i) && i >= 0 && i <= 100)
{
return i;
}
Console.WriteLine("Please enter a value between 0 and 100 inclusive");
}
}
int[] scores =
Enumerable
.Range(0, n)
.Select(x => AskForInteger())
.ToArray();
Console.WriteLine("The sum of all the scores is {0}", scores.Sum());
Console.ReadLine();
There are two options:
a. Start at 1 rather than 0 --> for (i = 1; i < n; i++)
b. Lower the value of n by 1 --> for (i = 1; i < n-1; i++)
Good luck

C# Need inputs in different lines

I am trying to create a program that is will take letters as input only and not duplicated. I am getting error when i put one letter in an input.
This is what i need to do, I need to get the user input in each line (like a enter, b enter, etc), if there is a duplication value i need a error message and continues with the input, and if there is incorrect value i get another error stating such. I cannot use LINQ, Hashset, nor list, it has to be arrays.
static void Main(string[] args)
{
char[] Array = new char[5];
Console.WriteLine("Please Enter 5 Letters B/W a through j only: ");
string letters = "abcdefghij";
char[] read = Console.ReadLine().ToLower().ToCharArray();
//loop through array
for (int i = 0; i < 5; i++)
{
if (letters.Contains(read[i]) && !Array.Contains(read[i]))
{
Array[i] = read[i];
}
else
{
Console.WriteLine("You have entered an incorrect value");
}
}
Console.WriteLine("You have Entered the following Inputs: ");
for (int i = 0; i < Array.Length; i++)
{
Console.WriteLine(Array[i]);
}
Console.ReadKey();
}
I think this more or less does what you want:
var max = 5;
var array = new char[max];
var letters = "abcdefghij";
var count = 0;
while (count < 5)
{
Console.WriteLine("Please Enter {0} Letters B/W a through j only: ", max);
var key = Console.ReadKey();
var read = key.KeyChar
if (!letters.Contains(read))
{
Console.WriteLine("You have entered an incorrect value");
continue;
}
var found = false;
for (int i = 0; i < count; i++)
{
if (array[i] == read)
{
found = true;
}
}
if (found)
{
Console.WriteLine("You have entered an duplicate value");
continue;
}
array[count++] = read;
}
Console.WriteLine("You have Entered the following Inputs: ");
for (int i = 0; i < array.Length; i++)
{
Console.WriteLine(array[i]);
}
Console.ReadKey();
If you want the user to enter the values individually then you would need to request each character in a loop.
Something like:
static void Main(string[] args)
{
const string validValues = "abcdefghij";
var enteredCharacters = new char[5];
for (int i = 0; i < enteredCharacters.Length; i++)
{
Console.WriteLine("Please enter a unique character between a and j");
var input = Console.ReadLine();
if (input.Length == 0)
{
Console.WriteLine("You did not enter a value.");
return;
}
if (input.Length > 1)
{
Console.WriteLine("You have entered more than 1 character");
return;
}
var character = input[0];
if (!validValues.Contains(character))
{
Console.WriteLine("You have entered an invalid character");
return;
}
if (enteredValues.Contains(character))
{
Console.WriteLine("You have already entered this character");
return;
}
enteredCharacters[i] = character;
}
// process numbers.
}
this is you problem
for (int i = 0; i < 5; i++)
this is your fix:
static void Main(string[] args)
{
char[] Array = new char[5];
Console.WriteLine("Please Enter 5 Letters B/W a through j only: ");
string letters = "abcdefghij";
char[] read = Console.ReadLine().ToLower().ToCharArray();
//loop through array
for (int i = 0; i < read.Length; i++)
{
if (letters.Contains(read[i]) && !Array.Contains(read[i]))
{
Array[i] = read[i];
}
else
{
Console.WriteLine("You have entered an incorrect value");
}
}
Console.WriteLine("You have Entered the following Inputs: ");
for (int i = 0; i < Array.Length; i++)
{
Console.WriteLine(Array[i]);
}
Console.ReadKey();
}

C# mastermind game

In the Main method, in the for loop, if you copy/paste/run whole program in visual, you'll see that i'm trying to end the game. First "if", if the user hasn't guessed; then attempts decrements by one and keeps guessing. The second "else if", if the user has guessed the PCArray, than the game ends and message shows. those work.
But, the first "else if", if the user has exhausted his attempts to guess, and hasn't guessed PCArray, than it should say "oh no, you couldn't guess..." Why is this not working.
I just want it to work so that if:
- user hasn't guessed but still has attempts, attempts decrements by 1 until 0.
- user has guessed the correct number, it says congrats.
- attempts are 0 and user still hasn't guessed number, then show "oh no..." message.
class Program
{
static void Main(string[] args)
{
string name;
Console.WriteLine("**************Let's play Master-Mined**************");
Console.WriteLine();
Console.Write("Please enter your name: ");
name = Console.ReadLine();
Console.WriteLine("Welcome {0}. Have fun!! ", name);
int numberCount = 0;
int difficultyLevel = 0;
int digitNumber = GetRandomNumberCount(numberCount);
Console.Write(digitNumber + " it is. Let's play.");
Console.WriteLine();
int[] PCArray = GenerateRandomNumbers(digitNumber);
Console.WriteLine("A " + digitNumber + "-digit number has been chosen. Each possible digit may be the number 1, 2, 3 or 4.");
Console.WriteLine(" ******");
int difficulty = GetGameDifficulty(difficultyLevel);
int attempts = difficulty * digitNumber;
Console.WriteLine("Enter your guess ({0} guesses remaining)", attempts);
int remaining = attempts;
for (int i = 0; i < attempts; i++)
{
int[] userArray = GetUserGuess(digitNumber);
int hits = CountHits(PCArray, userArray, attempts);
if ((hits != PCArray.Length) && (attempts > 0))
{
remaining--;
Console.WriteLine("Enter your guess ({0} guesses remaining)", remaining);
}
else if ((attempts < 1))
{
Console.WriteLine("Oh no {0}! You couldn't guess the right number.", name);
Console.WriteLine("The correct number is: ");
for (int j = 0; j < PCArray.Length; j++)
{
Console.Write(PCArray[j] + " ");
}
Console.WriteLine("Would you like to play again (Y/N)? ");
}
else if (hits == PCArray.Length)
{
attempts = 0;
Console.WriteLine("You win {0}!", name);
Console.WriteLine("The correct number is:");
for (int j = 0; j < PCArray.Length; j++)
{
Console.Write(PCArray[j] + " ");
}
}
}
Console.ReadLine();
}
public static int GetRandomNumberCount(int numberCount)
{
int number = 0;
do
{
try
{
Console.Write("How many numbers would you like to use in playing the game (4-10)? ");
number = int.Parse(Console.ReadLine());
Console.WriteLine();
}
catch
{
Console.WriteLine("You must pick a number between 4 and 10. Choose again.");
Console.WriteLine();
}
} while ((number < 4) || (number > 10));
return number;
}
public static int GetGameDifficulty(int difficultyLevel)
{
int difficulty = 0;
do
{
try
{
Console.Write("Choose a difficulty level (1=hard, 2=medium, 3=easy): ");
difficulty = int.Parse(Console.ReadLine());
}
catch
{
Console.WriteLine(" Incorrect entry: Please re-enter.");
}
} while ((difficulty < 1) || (difficulty > 3));
return difficulty;
}
public static int[] GenerateRandomNumbers(int PCSize)
{
int eachNumber;
int[] randomNumber = new int[PCSize];
Random rnd = new Random();
for (int i = 0; i < randomNumber.Length; i++)
{
eachNumber = rnd.Next(1, 5);
randomNumber[i] = eachNumber;
Console.Write(eachNumber);
}
Console.WriteLine();
return randomNumber;
}
public static int[] GetUserGuess(int userSize)
{
int number = 0;
int[] userGuess = new int[userSize];
for (int i = 0; i < userGuess.Length; i++)
{
Console.Write("Digit {0}: ", (i + 1));
number = int.Parse(Console.ReadLine());
userGuess[i] = number;
//Console.Write(number);
}
Console.WriteLine();
Console.Write("Your guess: ");
for (int i = 0; i < userGuess.Length; i++)
{
Console.Write(userGuess[i] + " ");
}
Console.WriteLine();
return userGuess;
}
public static int CountHits(int[] PCArray, int[] userArray, int attempts)
{
int hit = 0;
int miss = 0;
int hits = 0;
for (int i = 0; i < PCArray.Length; i++)
{
if (PCArray[i] == userArray[i])
{
hit = hit + 1;
hits = hit;
}
else
{
miss = miss + 1;
}
}
Console.WriteLine("Results: {0} Hit(s), {1} Miss(es)", hit, miss);
return hits;
}
}
First of all, you should rethink your code, because the flow control is scattered throughout your code. For example, you don't need both attempts and remaining, they control the same thing.
Using two variables to control the same thing is what is causing your problem. The first two ifs in your for should be like this:
if (hits != PCArray.Length && remaining > 1)
and
else if (remaining == 1)
Note I removed the unnecessary parenthesis. With these changes, your application works, although the code is not too pretty.
A simple way of enhancing your code is to first check for the right result, and if it's not, then decrease the attempts variable and finally check for its value. That's why with your code as it is, the if should compare to 1 instead of 0.
The hits variable in your CountHits method is totally unnecessary; you should just return hit. Actually the miss variable can be avoided too, you can calculate it. Also remember to use the ++ operator.
But as I said first, the important thing is not to make it work but to organize your code properly. Later I will post my version.
My version, it's not the most beautiful thing in the world but I didn't want to change much of your code structure:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("************** Let's play Master-Mind **************\n");
string name = GetPlayerName();
do
{
Play(name);
Console.Write("\nWould you like to play again (Y/N)? ");
}
while (Console.ReadLine().ToUpper() == "Y");
}
private static void Play(string name)
{
int numberCount = GetRandomNumberCount();
Console.Write(numberCount + " it is. Let's play.");
Console.WriteLine();
int[] PCArray = GenerateRandomNumbers(numberCount);
Console.WriteLine("A {0}-digit number has been chosen. Each possible digit may be the number 1 to 4.\n", numberCount);
int difficulty = GetGameDifficulty();
bool won = false;
for (int allowedAttempts = difficulty * numberCount; allowedAttempts > 0 && !won; allowedAttempts--)
{
Console.WriteLine("\nEnter your guess ({0} guesses remaining)", allowedAttempts);
int[] userArray = GetUserGuess(numberCount);
if (CountHits(PCArray, userArray) == numberCount)
won = true;
}
if (won)
Console.WriteLine("You win, {0}!", name);
else
Console.WriteLine("Oh no, {0}! You couldn't guess the right number.", name);
Console.Write("The correct number is: ");
for (int j = 0; j < numberCount; j++)
Console.Write(PCArray[j] + " ");
Console.WriteLine();
}
private static string GetPlayerName()
{
Console.Write("Please enter your name: ");
string name = Console.ReadLine();
Console.WriteLine("Welcome, {0}. Have fun!!\n", name);
return name;
}
public static int GetRandomNumberCount()
{
int number;
Console.Write("How many numbers would you like to use in playing the game (4-10)? ");
while (!int.TryParse(Console.ReadLine(), out number) || number < 4 || number > 10)
Console.WriteLine("You must pick a number between 4 and 10. Choose again.");
return number;
}
public static int GetGameDifficulty()
{
int difficulty = 0;
Console.Write("Choose a difficulty level (1=hard, 2=medium, 3=easy): ");
while (!int.TryParse(Console.ReadLine(), out difficulty) || difficulty < 1 || difficulty > 3)
Console.WriteLine("Incorrect entry: Please re-enter.");
return difficulty;
}
public static int[] GenerateRandomNumbers(int PCSize)
{
int eachNumber;
int[] randomNumber = new int[PCSize];
Random rnd = new Random();
Console.Write("PC number: ");
for (int i = 0; i < PCSize; i++)
{
eachNumber = rnd.Next(1, 5);
randomNumber[i] = eachNumber;
Console.Write(eachNumber);
}
Console.WriteLine();
return randomNumber;
}
public static int[] GetUserGuess(int userSize)
{
int number = 0;
int[] userGuess = new int[userSize];
for (int i = 0; i < userSize; i++)
{
Console.Write("Digit {0}: ", (i + 1));
while (!int.TryParse(Console.ReadLine(), out number) || number < 1 || number > 4)
Console.WriteLine("Invalid number!");
userGuess[i] = number;
}
Console.WriteLine();
Console.Write("Your guess: ");
for (int i = 0; i < userSize; i++)
{
Console.Write(userGuess[i] + " ");
}
Console.WriteLine();
return userGuess;
}
public static int CountHits(int[] PCArray, int[] userArray)
{
int hits = 0;
for (int i = 0; i < PCArray.Length; i++)
{
if (PCArray[i] == userArray[i])
hits++;
}
Console.WriteLine("Results: {0} Hit(s), {1} Miss(es)", hits, PCArray.Length - hits);
return hits;
}
}
It does a few more validations and it even actually lets you play again! ;)

Categories

Resources