Queue that stores User's entered Array and displays it - c#

So i have a simple program that i have set up to ask the user for an array size then it gets them to enter the elements then prints them, i would like to set up a Queue so it prints a whole of the array, for example.
History
1 2 3 4 //Length of the Array
3 4 5 6 //User Guess for this round
After this every time the user re enters the array that array would show up in the history also.
History
1 2 3 4 //Length of the Array
3 4 5 6 //User Guess for this round
2 6 7 8 //User second input
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Random_test
{
class Program
{
public int n;
public int[] UserArray;
public int i;
public int reEnter;
public int rear = -1;
public int front = -1;
public int[] history;
public void main()
{
Console.WriteLine("Please enter the Length of Your array");
n = Convert.ToInt32(Console.ReadLine());
UserArray = new int[n];
history = new int[n];
do
{
for (i = 0; i < n; i++)
{
Console.WriteLine("Your Elements");
UserArray[i] = Convert.ToInt32(Console.ReadLine());
}
for (i = 0; i < n; i++)
{
Console.WriteLine("Your Array: {0} ", UserArray[i]);
}
Console.WriteLine("Would you like to re-enter your array");
reEnter = Convert.ToInt32(Console.ReadLine());
for (i = 0; i < 1; i++)//loop for history
{
insert();
delete();
showHistory();
}
} while (reEnter == 1);
}
public void insert()
{
if (rear == -1)
{
front = 0;
rear++;
history[rear] = UserArray[i];
}
else
{
rear++;
history[rear] = UserArray[i];
}
}
public void delete()
{
if (front == -1)
{
Console.WriteLine("There is no history availible");
}
else
{
front++;
}
}
public void showHistory()
{
if (rear == -1)
{
Console.WriteLine("There is no history availible");
}
else
{
Console.WriteLine("History");
for (int i = 0; i < n; i++)
{
Console.Write(" {0} ");
Console.Write(" - ");
Console.WriteLine(" {0} ", history[i]);
}
}
}
static void Main(string[] args)
{
Program main = new Program();
main.main();
Console.WriteLine("Game Over");
Console.ReadKey();
}
}
}
This was just a quick jot up program as you can see i have attempted to do the Queue, it works but prints only the first element of the User Array each turn. Unfortunately this is where i do not know how implement what i talked about at the start of the post. I would like to stick to this method of creating the Queues, i do not want to use the queue class, the idea is to keep it clean and simple.
Many Thanks.

Sorry for my evil comments before. I think this might suite your level... happy coding.
public class Program
{
static void Main(string[] args)
{
(new Program()).Ask();
}
private void Ask()
{
string history = "";
while (true)
{
Console.Write("Len > ");
int len = int.Parse(Console.ReadLine());
int[] arr = new int[len];
for (int i = 0; i < len; i++)
{
Console.Write("El{0} > ", i);
arr[i] = int.Parse(Console.ReadLine());
}
Console.WriteLine();
string str = string.Join(",", arr);
Console.WriteLine("Arr > {0}", str);
Console.WriteLine("His > {0}", history);
history += string.Format("[{0}] ", str);
Console.WriteLine("Again?");
if (Console.ReadLine().Length == 0)
break;
Console.WriteLine();
}
}
}

Related

Write a program in C# and ask the user to enter 5 unique numbers

Write a program and ask the user to enter 5 numbers. If a number has
been previously entered, display an error message and ask the user to
retry. Once the user successfully enters 5 unique numbers, sort them
and display the result on the console.
Can anybody please help me on this one? I'm really confused on how to solve this. Here's my code:
var number = new int[5];
Console.WriteLine("Enter 5 unique numbers");
for (int i = 0; i < 5; i++)
{
number[i] = Convert.ToInt32(Console.ReadLine());
var numberValue = number[i];
var currentNumber = Array.IndexOf(number, numberValue);
if (number[i] == number[0])
{
continue;
}
else
{
if (!(currentNumber == number[i]))
{
continue;
}
else
{
Console.WriteLine("Hold on, you already entered that number. Try again.");
}
}
/* foreach (var n in number) { ... } */
continue;
}
Array.Sort(number);
Console.WriteLine();
foreach (var n in number)
Console.WriteLine(n);
Console.WriteLine();
I can't find the solution on the checking if there is already the same number input. Help me please. And please explain why it is the answer.
PS: Can you please only use simple code and do not use keywords like HashSet? I know that will solve the problem but I don't know it yet. I'm just trying to learn C# step by step so I'm sorry for that.. Thank you!
Let's extract a method and use a HashSet<int> to ensure numbers being unique:
using System.Linq; // We are going to use .ToArray()
...
private static int[] ReadUniqueNumbers(int count) {
HashSet<int> numbers = new HashSet<int>();
Console.WriteLine($"Enter {count} unique numbers");
while (numbers.Count < count) {
int number = 0;
if (!int.TryParse(Console.ReadLine(), out number))
Console.WriteLine("Syntax error. Not a valid integer value. Try again.");
else if (!numbers.Add(number))
Console.WriteLine("Hold on, you already entered that number. Try again.");
}
// Or if you want ordered array
// return numbers.OrderBy(item => item).ToArray();
return numbers.ToArray();
}
...
int[] number = ReadUniqueNumbers(5);
Edit: Let's use good old loops, without HashSet and Linq:
private static int[] ReadUniqueNumbers(int count) {
int[] result = new int[count];
int numberCount = 0;
while (numberCount < count) {
int number = 0;
// When working with user input we should be ready for any string:
// user may well input "bla-bla-bla" (not an integer at all)
if (!int.TryParse(Console.ReadLine(), out number))
Console.WriteLine("Syntax error. Not a valid integer value. Try again.");
else {
bool found = false;
// Do we have duplicates?
// Linq (for reference only)
// found = result.Take(numberCount).Any(item => item == number);
for (int i = 0; i < numberCount; ++i)
if (result[i] == number) {
found = true;
break;
}
if (found) // Duplicate found
Console.WriteLine("Hold on, you already entered that number. Try again.");
else {
result[numberCount] = number;
numberCount += 1;
}
}
}
return result;
}
var number = new int[5];
Console.WriteLine("Enter 5 unique numbers");
for (int i = 0; i < 5; i++)
{
while (true)
{
var newValue = Convert.ToInt32(Console.ReadLine());
var currentNumber = Array.IndexOf(number, newValue);
if (currentNumber == -1)
{
number[i] = newValue; // Accept New value
break;
}
Console.WriteLine("Hold on, you already entered that number. Try again.");
}
}
Array.Sort(number);
Console.WriteLine();
foreach (var n in number)
Console.WriteLine(n);
Console.ReadLine();
Array.IndexOf() returns index of numberValue in array, or -1 if it does not exist.
for (int i = 0; i < 5; i++)
{
var numberValue = Convert.ToInt32(Console.ReadLine());
var currentNumberIndex = Array.IndexOf(number, numberValue);
if (currentNumberIndex >= 0)
{
Console.WriteLine("Hold on, you already entered that number. Try again.");
i--;
}
else
{
number[i] = numberValue;
}
}
Array.IndexOf() returns index of numberValue in array, or -1 if it does not exist
List<Int32> Numbers=new List<Int32>();
Console.WriteLine("Enter 5 unique numbers");
while (Numbers.Count<5) {
int result=-1;
Boolean IsNumber=Int32.TryParse(Console.ReadLine(),out result);
if (IsNumber==false) {
Console.WriteLine("Please enter a number!!!");
continue;
}
if (Numbers.IndexOf(result)>=0) {
Console.WriteLine("Hold on, you already entered that number. Try again.");
continue;
}
Numbers.Add(result);
}
Others have already pasted their answers, but here goes my strategy. It uses a nullable array and Contains to avoid iterating through the numbers in the array each time the user types a number.
static void Main(string[] args)
{
var numbers = new int?[5];
for (int i = 0; i < 5; i++)
{
Console.WriteLine($"Please enter number {i+1}.");
do
{
int n;
while (!int.TryParse(Console.ReadLine(), out n))
Console.WriteLine("Invalid number. Please try again.");
var currentNumber = Convert.ToInt32(n);
var containsNumber = numbers.Contains(currentNumber);
if (!containsNumber)
{
numbers[i] = currentNumber;
break;
}
Console.WriteLine("Number was entered previously, please enter a different number.");
} while (true);
}
Console.Clear();
Array.Sort(numbers);
foreach (int? n in numbers)
Console.WriteLine(n);
Console.ReadLine();
}
var input = new HashSet<int>(); // accepts only unique values
while (input.Count() < 5)
{
Console.WriteLine("enter value");
int temp; // In newer C# it can be moved to TryParse e.g "out int temp"
if (Int32.TryParse(Console.ReadLine(), out temp))
{
if (input.Contains(temp))
{
Console.WriteLine("this number is already in collection");
}
else
{
input.Add(temp);
}
}
else
{
Console.WriteLine("incorrect value");
}
}
// order by(lambda_expression) allows you to specify by "what things"
// you'd want to order that collection. In this case you're just sorting
// by numbers, but if it was complex objects collection then you'd be
// able to sort by e.g student => student.Money; which would mean that
// you're sorting students by their Money count.
foreach (var number in input.OrderBy(x => x))
{
Console.WriteLine(number);
}
public static void Main (string[] args) {
var numbers = new List<int>();
while(numbers.Count() < 5)
{
var line = Console.ReadLine();
int number;
if (int.TryParse(line, out number)) {
if (numbers.Contains(number))
Console.WriteLine("You already entered " + line);
else
numbers.Add(number);
} else
Console.WriteLine(line + " is not a number");
}
Console.WriteLine(string.Join(", ", numbers.OrderBy(i => i)));
}
using System;
using System.Collections.Generic;
namespace exercise2
{
class Program
{
static void Main(string[] args)
{
//exercise 2 : question 3
Console.WriteLine("Please write 5 numbers");
var array = new int[5];
const int loop_leng = 5;
for(var i = 0; i < loop_leng; i++)
{
var input = Console.ReadLine();
if(string.IsNullOrWhiteSpace(input))
{
Console.WriteLine("Re-try");
break;
}
int numbers = Convert.ToInt32(input);
foreach (var x in array)
{
if (numbers == x)
{
Console.WriteLine("don't repeat! re-try..");
break;
}
}
array[i] = numbers;
var a = Array.IndexOf(array, numbers);
var b = Array.LastIndexOf(array, numbers);
if(a != b)
{
if(array[a] == array[i])
{
break;
}
}
}
{
Console.WriteLine();
Array.Sort(array);
foreach (var n in array)
Console.WriteLine(n);
}
}
}
}
}
using System;
using System.Linq;
namespace ControlFlow
{
internal class Program
{
private static void Main(string[] args)
{
var numbers = new int[5];
for (var i = 0; i < 5; i++)
{
Console.WriteLine("Enter 5 Numbers:");
var checkThisNumber = Convert.ToInt32(Console.ReadLine());
if (numbers.Contains(checkThisNumber))
{
i -= 1;
continue;
}
numbers[i] = checkThisNumber;
}
Array.Sort(numbers);
foreach (var num in numbers)
{
Console.WriteLine(num);
}
}
}
}
You have a problem. You can divide this into four steps:
Read input from the console.
Check if it is a valid integer.
Check if it has been entered before.
Repeat until the required number of unique integers are obtained.
You can write functions for each of these subtasks:
public static int?[] ReadUniqueIntegers(int count)
{
int?[] uniqueNumbers = new int?[count];
for (int i = 0; i < count; i++)
{
int number = ReadIntegerFromConsole();
// If the number entered above already exists, the IsIntegerAlreadyExisting will return true and the while loop runs until a unique value is entered
while (IsIntegerAlreadyExisting(number, uniqueNumbers))
{
Console.WriteLine("Integer already entered. Enter a unique integer:");
number = ReadIntegerFromConsole();
}
uniqueNumbers[i] = number;
}
return uniqueNumbers;
}
Now you need the functions for the subtasks:
public static int ReadIntegerFromConsole()
{
// Read line as string
Console.WriteLine("Enter an integer");
String input = Console.ReadLine();
int inputAsInteger;
// Keep reading console input until it is a valid integer
while (!int.TryParse(input, out inputAsInteger) {
Console.WriteLine("Invalid input. Please enter an integer");
input = Console.ReadLine();
}
return inputAsInteger;
}
public static bool IsIntegerAlreadyExisting(int newInteger, int[] numbers)
{
foreach (var integer in numbers)
{
if (integer == newInteger)
{
// an existing integer is the same as the newly entered integer
return true;
}
}
// no integer equals the new integer
return false;
}
Now you can use your ReadUniqueNumbers() like this:
int[] fiveUniqueNumbers = ReadUniqueNumbers(5);
The default value of an int in an array is 0. So, if you create a new array of size 5, it will by default contain five 0s. And if you enter 0, you will get it already exists even for the first time. To prevent this, use int?[] instead of int[]. An int?[] (nullable int) array will have a default value of null instead of 0.
Full Code
public class Program
{
public static int?[] ReadUniqueIntegers(int count)
{
int?[] uniqueNumbers = new int?[count];
for (int i = 0; i < count; i++)
{
int number = ReadIntegerFromConsole();
// If the number entered above already exists, the IsIntegerAlreadyExisting will return true and the while loop runs until a unique value is entered
while (IsIntegerAlreadyExisting(number, uniqueNumbers))
{
Console.WriteLine("Integer already entered. Enter a unique integer:");
number = ReadIntegerFromConsole();
}
uniqueNumbers[i] = number;
}
return uniqueNumbers;
}
public static int ReadIntegerFromConsole()
{
// Read line as string
Console.WriteLine("Enter an integer");
String input = Console.ReadLine();
int inputAsInteger;
// Keep reading console input until it is a valid integer
while (!int.TryParse(input, out inputAsInteger )) {
Console.WriteLine("Invalid input. Please enter an integer");
input = Console.ReadLine();
}
return inputAsInteger;
}
public static bool IsIntegerAlreadyExisting(int newInteger, int?[] numbers)
{
foreach (var integer in numbers)
{
if (integer == newInteger)
{
// an existing integer is the same as the newly entered integer
return true;
}
}
// no integer equals the new integer
return false;
}
public static void Main()
{
int?[] numbers = ReadUniqueIntegers(5);
Console.WriteLine("Entered numbers are: ");
foreach (var number in numbers)
{
Console.Write(number + " ");
}
}
}

Trying to create a histogram by using a string to print out the same amount of times equal to the value of an integer user input

Im completely new to coding and I've been given a challenge to create a histogram by asking a user to input a certain amount of numbers line by line. Which I have executed a for loop to handle with no issues. The difficulty I'm having is I'm trying to use a string which I've called (x) and contains (""). The challenge is to make the () symbol duplicate to the amount of the value entered by the user... Just wondering how I could code it in such a way so that it compares the user input value number to print the (*) the same amount equal to the number being entered!
namespace Exercise_4
{
class Program
{
static void Main(string[] args)
{
int[] userVal = new int[8];
string x = ("*");
for (int count = 0; count < userVal.Length; count++)
{
if (userVal[count] <= 10)
{
Console.WriteLine("Please enter Number");
userVal[count] = int.Parse(Console.ReadLine());
}
else
{
Console.WriteLine("ERROR, Number too BIG!");
}
}
for (int count= 0; count < userVal.Length; count ++)
{
}
A simple way might be to iterate through the responses, and use the string(char,cnt) constructor https://msdn.microsoft.com/en-us/library/xsa4321w(v=vs.110).aspx.
It fills the string with a specific char, and specific length.
e.g.
namespace Exercise_4
{
class Program
{
static void Main(string[] args)
{
int numberToCollect = 10;
int[] answers = new int[numberToCollect];
int numberCollected = 0;
while(numberCollected<numberToCollect)
{
int parsedInt = 0;
if (int.TryParse(intConsole.ReadLine(),out parsedInt))
{
answers[numberCollected++] = parsedInt;
}
else
{
Console.WriteLine("Invalid number, try again!");
}
}
for(var cnt in answers)
{
Console.WriteLine(new String('*',cnt));
}
}
}
}
namespace Exercise_4
{
class Program
{
static void Main(string[] args)
{
int[] userVal = new int[8];
for (int count = 0; count < userVal.Length; count++)
{
if (userVal[count] <= 10)
{
Console.WriteLine("Please enter Number");
userVal[count] = int.Parse(Console.ReadLine());
}
else
{
Console.WriteLine("ERROR, Number too BIG!");
}
}
foreach (var cnt in userVal)
{
Console.WriteLine(new String('*', cnt));
}
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! ;)

C# create and manipulate an array of Employee objects

Create:
This class defines an Employee.
Member variables: ID (int), name (string), salary (double)
Member Methods: Constructors, input/output methods that perform I/O for an employee
Create:
This class defines an array of Employees
Member variables: An array of Employee, SIZE (int), currentSize (int)
Member Methods: Constructors, input/output methods, search/insert/delete/update methods.
Not sure exactly how to store 3 Employee variables inside a single array index.
Updated:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication16
{
class Employee
{
protected int id;
protected string name;
protected double salary;
public Employee()
{
}
public Employee(int _id, string nm, double sal)
{
id = _id;
name = nm;
salary = sal;
}
public void PrintEmployee()
{
Console.WriteLine("id: {0}", id);
Console.WriteLine("Name: {0}", name);
Console.WriteLine("Salary: {0}", salary);
}
}
class EmployeeArray : Employee
{
private Employee[] a;
private int currSize;
private const int SIZE = 100;
public EmployeeArray()
: base()
{
}
public EmployeeArray(int s, int _id, string nm, double sal)
: base(_id, nm, sal)
{
a = new Employee[SIZE];
if (s > SIZE)
Console.WriteLine("Array size is overflow!");
else if (s == SIZE)
Console.WriteLine("Array is full.");
else
currSize = s;
}
public void Input()
{
a = new Employee[3];
for (int i = 0; i < currSize; i++)
{
a[i] = new Employee(id, name, salary);
}
}
public void Output()
{
Console.WriteLine("Array is: ");
foreach (Employee x in a)
Console.WriteLine("a[{0}]= {1}", name, x);
}
public int Search(int key)
{
for (int i = 0; i < currSize; i++)
{
//if (a[i] == key)
// return i;
}
return -1;
}
public void Insert()
{
if (currSize == SIZE)
{
Console.Write("Array is full! ");
return;
}
Console.WriteLine("Enter a number to insert: ");
int y = int.Parse(Console.ReadLine());
Console.Write("Enter the index to where it is to insert: ");
int pos = int.Parse(Console.ReadLine());
for (int i = currSize; i > pos; i--)
a[i] = a[i - 1];
//a[pos] = y;
currSize++;
}
public void Delete()
{
if (currSize == 0)
{
Console.WriteLine("Array is empty! ");
return;
}
Console.Write("Delete by value (1) or by index (2): ");
int key = int.Parse(Console.ReadLine());
int pos = -1;
if (key == 1)
{
Console.WriteLine("Enter the number to delete: ");
int d = int.Parse(Console.ReadLine());
pos = Search(d);
while (pos == -1)
{
Console.WriteLine("The number does not exist, enter again: ");
d = int.Parse(Console.ReadLine());
pos = Search(d);
}
}
else if (key == 2)
{
Console.WriteLine("Enter the index to delete from: ");
pos = int.Parse(Console.ReadLine());
while (pos < 0 || pos > currSize)
{
Console.WriteLine("The index is out of range, enter again: ");
pos = int.Parse(Console.ReadLine());
}
}
else
return;
for (int i = pos; i < currSize; i++)
a[i] = a[i + 1];
currSize--;
if (currSize <= 0)
Console.Write("Array is empty! ");
}
public void Update()
{
Console.WriteLine("Enter the index where to update: ");
int pos = int.Parse(Console.ReadLine());
while (pos < 0 || pos >= currSize)
{
Console.WriteLine("The index you entered is not valid, enter again: ");
pos = int.Parse(Console.ReadLine());
}
Console.WriteLine("Enter the new value: ");
int x = int.Parse(Console.ReadLine());
//a[pos] = x;
Console.Write("Update complete! ");
}
}
class Program
{
//static char ShowMenu()
//{
// Console.WriteLine("\nEnter the letter of operation: \n(o)Print, (s)Search, (i)Insertion, (d)Deletion, (u)Update, (e)Exit\n");
// return char.Parse(Console.ReadLine());
//}
static void Main(string[] args)
{
//char sel = ' ';
Console.Write("Enter number of Employees; ");
int i = 0;
int s = int.Parse(Console.ReadLine());
while ( i < s )
{
Console.WriteLine("");
Console.WriteLine("");
Console.WriteLine("Enter id: ");
int _id = int.Parse(Console.ReadLine());
Console.WriteLine("");
Console.WriteLine("Enter Name: ");
string nm = Console.ReadLine();
Console.WriteLine("");
Console.WriteLine("Enter Salary: ");
double sal = int.Parse(Console.ReadLine());
EmployeeArray arr = new EmployeeArray(s, _id, nm, sal);
i++;
}
}
}
}
This reads like homework but I'll help you out.
You create your employee class with it's three members and methods.
then you create an array of employee objects.
//How Many employee objects do you need. Let's assume 10 for example
int NUM = 10;
Employee[] employees = new Employee[NUM]; // Declare an An array of employee's of length 10 (zero indexed from 0 - 9)
//Assuming you have made Getters and Setters
//Then if you need to access an employee object's member(s)
employees[0].getId(); //get the first employee's id
employees[0].getName(); //get the first employee's name
employees[0].getSalary(); //get the first employee's name
// Or set them like
employees[4].setId(12); //set the fifth employee's id to 12
employees[4].setName("Joe Bloggs"); //set the fifth employee's name to Joe Bloggs
employees[4].setSalary("30000"); //set the fifth employee's salary to 30000
MSDN C# Arrays
MSDN Classes
There are lots of problems with the code you posted. I'm just going to highlight a few issues, especially since this implementing arrays sounds a lot like computer science homework.
EmployeeArray inherits from Employee. Think about the meaning of public and private keywords and base classes.
Your functions all do more than one thing. This really complicates your code, and is going to result in bugs. Focus on straightforward code that does one thing and communicates what it does.
Users could crash your program in several places by entering something other than a number.
Lastly, to directly answer your question, you can access arrays through an index. You can't store three separate Employee objects in the same index. You've accessed array objects in other parts of your code, so it seems like you understand that you can store different values in different indexes.

Get highest number from inputs

I need a programm, where I can type in numbers and in the end it gives me the highest number.
Why doesn't it work like that? What do I need to change?
public class Program
{
public static void Main()
{
double[] input = new double[12];
for (int i = 1; i <= 12; i++)
{
Console.Write(" Type in {0} number:", i);
input = [Convert.ToInt32(Console.ReadLine())];
}
Console.WriteLine("The highest number is {0}", input.Max(element => Math.Abs(element)));
Console.ReadKey();
}
}
You need to make it so its converting to double and also setting to each individual element
input[i] = Convert.ToDouble(Console.ReadLine());
and then change this because arrray starts at 0
for (int i = 0; i <= 11; i++)
As #Ashad Shanto said you must use Convert.ToDouble and you must use input[i] instead of input. So your code should look like:
public class Program
{
public static void Main()
{
double[] input = new double[12];
for (int i = 0; i < 12; i++)
{
Console.Write(" Type in {0} number:", i);
input[i] = [Convert.ToDouble(Console.ReadLine())];
}
Console.WriteLine("The highest number is {0}", input.Max(element => Math.Abs(element)));
Console.ReadKey();
}
}
Is the requirement to have a Double or Int? Anyways, you can just simple store the highest number each time a new number is entered by doing a simple comparison.
public static void Main()
{
var currentNumber = 0;
for (var i = 1; i <= 12; i++)
{
Console.Write(" Type in {0} number: ", i);
var number = Console.ReadLine();
int result;
if (int.TryParse(number, out result))
{
if (currentNumber < result)
{
currentNumber = result;
}
}
}
Console.WriteLine("The highest number is {0}", currentNumber);
Console.ReadKey();
}
As #artokai mentioned you don't need to store all entered numbers.
Try the following:
double heighest = Double.MinValue;
for (int i = 0; i < 12; i++)
{
Console.Write(" Type in {0} number:", i);
double input = (Convert.ToDouble(Console.ReadLine());
if (input > heighest)
heighest = input
}
Console.WriteLine("The highest number is {0}", highest);

Categories

Resources