I Have the first part of my code pretty complete and I got the gist of the rest, I'm just not sure how to put it all together. Here is the first part
using System;
namespace ConsoleApplication1
{
class Program
{
public class AccountInfo
{
public int Number { get; set; }
public double Balance { get; set; }
public string LastName { get; set; }
}
static void Main(string[] args)
{
List<AccountInfo> accounts = new List<AccountInfo>();
for (int index = 1; index < 6; index++)
{
AccountInfo acc = new AccountInfo();
Console.Write("Enter account number: " + index.ToString() + ": ");
acc.Number = int.Parse(Console.ReadLine());
Console.Write("Enter the account balance: ");
acc.Balance = double.Parse(Console.ReadLine());
Console.Write("Enter the account holder last name: ");
acc.LastName = Console.ReadLine();
accounts.Add(acc);
}
}
}
}
The second part is to ask the user what they want to do with the arrays
enter an a or A to search account numbers
enter a b or B to average the accounts
enter an x or X to exit program
the search part I can use something like this:
public void search Accounts()
{
for(int x = 0; x < validValues.Lenth; ++x)
{
if(acctsearched == validValues[x])
{
isValidItem = true;
acctNumber = Number[x];
}
}
And I can use a while loop with a bool true/false to close out.
I'm not sure how to get the average balance. I keep getting errors like "can't implicitly change int[] to int"
Any help with this would very much appreciated.
Sounds like you have an List of AccountInfo. Are you able to use LINQ?
To get the average, you can do this with LINQ:
double avg = accounts.Select(x=>x.Balance).Average();
To search for a given acct, you can do something like this:
var foundAcct = accounts.SingleOrDefault(x=>x.Number==someSearchNum);
For this to work(and create methods for these 2 actions), you'd need to move the List<AccountInfo> accounts out of the Main and be declared in the class.
With LINQ, you'll required .NET 3.5 or greater.
using System;
namespace AssignmentWeek3
{
class Accounts
{
// private class members, creating new arrays
private int [] AcctNumber = new int[5];
private double [] AcctBalance = new double[5];
private string [] LastName = new string[5];
public void fillAccounts()//fill arrays with user input
{
int x = 0;
for (int i = 0; i < AcctNumber.Length; i++)
{
Console.Write("Enter account number: ");
AcctNumber[x] = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter account balance: ");
AcctBalance[x] = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter account holder last name: ");
LastName[x] = Convert.ToString(Console.ReadLine());
x++;
}
}
public void searchAccounts() //search account method to be called later in main()
{
int accountNum = 0;
bool isValid = false;
int x = 0;
Console.Write("Please enter account number to search for: ");
accountNum = Convert.ToInt32(Console.ReadLine());
while (x < AcctNumber.Length && accountNum != AcctNumber[x])
++x;
if(x != AcctNumber.Length)
{
isValid = true;
}
if(isValid){
Console.WriteLine("AcctNumber: {0} Balance: {1:c} Acct Holder: {2}", AcctNumber[x], AcctBalance[x], LastName[x]);
}
else{
Console.WriteLine("You entered an invalid account number");
}
}
public void averageAccounts()//averageAccounts method to be store for later use
{
// compute and display average of all 5 bal as currency use length.
int x = 0;
double balanceSum = 0;
double Avg = 0;
for (x = 0; x < 5; x++ )
{
balanceSum = balanceSum + AcctBalance[x];
}
Avg = (balanceSum / x);
Console.WriteLine("The average balance for all accounts is {0:c}", Avg);
}
} //end public class Accounts
class week3_assignment //Main class
{
static void Main()
{
char entry = '0';
//instantiate one new Accounts object
Accounts accounts = new Accounts();
//call class methods to fill Accounts
accounts.fillAccounts();
//menu with input options
bool Exit = false;
while (!Exit)
{
while (entry != 'x' && entry != 'X')
{
Console.WriteLine("*****************************************");
Console.WriteLine("enter an a or A to search account numbers");
Console.WriteLine("enter a b or B to average the accounts");
Console.WriteLine("enter an x or X to exit program");
Console.WriteLine("*****************************************");
entry = Convert.ToChar(Console.ReadLine());
switch (entry) //set switch
{
case 'a':
case 'A':
accounts.searchAccounts();//calls search accounts method
break;
case 'b':
case 'B':
accounts.averageAccounts();//calls average accounts method
break;
case 'x':
case 'X':
(Exit) = true;
break;
default:
Console.WriteLine("That is not a valid input");
break;
}
}
}
}
}
}
Related
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 + " ");
}
}
}
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();
}
}
}
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.
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();
}
}
}
My code asks the user to enter a certain amount of students and to enter there name and score depends on how many students there are. My question is, how would I use an if statement to find out the student with the highest score. (C#)
class Class1
{
public void studentCount()
{
int studentcount;
int i;
int x;
string studentname = "";
Console.WriteLine("Enter how many students there are: ");
studentcount = Convert.ToInt32(Console.ReadLine());
{
for (i = 1; i <= studentcount; i++)
{
Console.WriteLine("Enter students name: ");
studentname = Convert.ToString(Console.ReadLine());
Console.WriteLine("Enter students score: ");
x = Convert.ToInt32(Console.ReadLine());
}
}
Keep track of the current highest x (student's score) and if a new one that's entered is higher than the last highest, update the last highest score's variable and that student's name. You'll need to use one more variable for this to keep track of the current max score. You can always update the student's name to match the student with the max score. After the loop, you can output that student's score and name.
Respecting your actual code, probably this would suit you well.
int studentcount = 0, i = 0, x = 0, highestScore = 0;
string studentname = "", highestScoreStudentName = "";
Console.WriteLine("Enter how many students there are: ");
studentcount = Convert.ToInt32(Console.ReadLine());
{
for (i = 1; i <= studentcount; i++)
{
Console.WriteLine("Enter students name: ");
studentname = Convert.ToString(Console.ReadLine());
Console.WriteLine("Enter students score: ");
x = Convert.ToInt32(Console.ReadLine());
if (x > highestScore)
{
highestScore = x;
highestScoreStudentName = studentname;
}
}
}
There are many ways to accomplish this. Below are a few ways. Best would be the take advantage of OOP and create classes for what you need to do, but of course there are other ways to do what you want.
Sticking with your current method:
public void studentCount()
{
string highestScoringStudent;
int highestScore = 0;
Console.WriteLine("Enter how many students there are: ");
var studentCount = Convert.ToInt32(Console.ReadLine());
for (var i = 0; i < studentCount; i++)
{
Console.WriteLine("Enter students name: ");
var tempStudent = Convert.ToString(Console.ReadLine());
Console.WriteLine("Enter students score: ");
var tempScore = Convert.ToInt32(Console.ReadLine());
if(tempScore > highestScore)
{
highestScore = tempScore;
highestScoringStudent = tempStudent;
}
}
}
With a dictionary to keep track of your students:
public void StudentCount()
{
var students = new Dictionary<string, int>();
var count = Convert.ToInt32(Console.ReadLine());
for (var i = 0; i < count; i++)
{
Console.WriteLine("Enter Student's Name:");
var name = Console.ReadLine();
Console.WriteLine("Enter Student's Score:");
var score = Convert.ToInt32(Console.ReadLine());
students.Add(name, score);
}
var highestStudent = students.OrderByDescending(x => x.Value).FirstOrDefault()
Console.WriteLine("{0} scored {1}", highestStudent.Key, highestStudent.Value);
}
Using OOP:
public class TestEntry
{
public string StudentName { get; set; }
public int Score { get; set; }
}
public class SomeClass
{
readonly List<TestEntry> _testEntries = new List<TestEntry>();
public void EnterTests()
{
_testEntries.Clear();
var count = Convert.ToInt32(Console.ReadLine());
for (var i = 0; i < count; i++)
{
Console.WriteLine("Enter Student's Name:");
var testEntry = new TestEntry();
testEntry.StudentName = Console.ReadLine();
Console.WriteLine("Enter Student's Score:");
testEntry.Score = Convert.ToInt32(Console.ReadLine());
_testEntries.Add(testEntry);
}
}
public void PrintHighestScoringStudent()
{
var highestTest = _testEntries.OrderByDescending(x => x.Score).FirstOrDefault();
if (highestTest == null)
{
Console.WriteLine("No tests entered.");
return;
}
Console.WriteLine("{0} scored {1}", highestTest.StudentName, highestTest.Score);
}
}
use array [] and sort it then top most value is higher
Everton's solution will work, but I would think that you might be interested in keeping track of all scores. In that case, you could use an Array as suggested, but a better solution is probably to use a SortedList.
SortedList<int> students = new SortedList<int>();
...
for (int i = 0; i < studentcount; i++)
{
Console.WriteLine("Enter students name: ");
studentname = Convert.ToString(Console.ReadLine());
Console.WriteLine("Enter students score: ");
x = Convert.ToInt32(Console.ReadLine());
students.Add(x);
}
int max = students.Last; //Default sorting is low to high,
//though this could be changed if
//you want to look into it.
If you wanted to keep track of scores with respect to the student, you could use a List<Tuple<string, int>>, but without some finagling it would not be possible to sort it. However, using Linq finding the max value is not difficult.
List<Tuple<string, int> >students = new List<Tuple<string, int> >();
...
for (int i = 0; i < studentcount; i++)
{
Console.WriteLine("Enter students name: ");
studentname = Convert.ToString(Console.ReadLine());
Console.WriteLine("Enter students score: ");
x = Convert.ToInt32(Console.ReadLine());
students.Add(studentname, x);
}
int max = students.Max(a => a.Item2).FirstorDefault();