I'm taking a C# class this semester and it has been quite fun so far. I have an assignment where I need to do several things with an array: add numbers in the array, see the numbers entered in the array, find a number in the array, sort the numbers in the array, create statistics based on the array numbers, and finally exit the application.
So far I have been having a little bit of an issue with adding numbers to the array while making sure that the data entered is only numbers. I think I am about to figure it out, but help is always appreciated. And, does my findData() method look ok?
Thank you again for your time in reading this question!
class Program
{
static char myChoice = Console.ReadKey().KeyChar;
static double[] myArray = new double[100];
static void Main(string[] args)
{
while (true)
{
Console.WriteLine("Welcome to Lab 2");
Console.WriteLine();
Console.WriteLine("Main Menu");
Console.WriteLine("1- Add new data");
Console.WriteLine("2- See all data");
Console.WriteLine("3- Find a number");
Console.WriteLine("4- Sort the data");
Console.WriteLine("5- Create statistics");
Console.WriteLine("6- Exit Program");
switch (myChoice)
{
case '1':
Console.WriteLine("1- Add new data");
addData();
break;
case '2':
Console.WriteLine("2- See all data");
seeData();
break;
case '3':
Console.WriteLine("3- Find a number");
findData();
break;
case '4':
Console.WriteLine("4- Sort the data");
sortData();
break;
case '5':
Console.WriteLine("5- Create statistics");
createData();
break;
case '6':
Console.WriteLine();
exitProgram();
break;
}
}
}
//This method will add numbers to the array
public static void addData()
{
bool isNumber = false;
double number;
double temp;
for (int i = 0; i < myArray.Length; i++)
{
Console.WriteLine("Enter a number you would like to add");
myArray[i] = Convert.ToDouble(Console.ReadLine());
temp = myArray[i];
if (!Double.TryParse(temp, out number))
{
Console.WriteLine("Invalid input. Please enter a valid number")
}
else
{
}
}
}
//This method will see the numbers entered in the array
public static void seeData()
{
foreach (var item in myArray)
{
Console.WriteLine(item.ToString());
}
}
//This method will find a specific number within the array and check if it has already been entered
public static void findData()
{
Console.WriteLine("Find a number");
string myChoice = Console.ReadLine();
double number;
bool isNumber = Double.TryParse(myChoice, out number);
{
}
}
//This method will sort the array ascending to descending
public static void sortData()
{
Console.WriteLine("The array has been sorted in ascending order");
Array.Sort(myArray);
Console.WriteLine("The array has been sorted in descending order");
Array.Reverse(myArray);
}
//This method will create statistics based on the numbers in the array
public static void createData()
{
//Sum
double sum = myArray.Sum();
Console.WriteLine("The total sum of the array is: " + sum);
//Average
double average = sum / myArray.Length;
Console.WriteLine("The average number of the array is: " + average);
//Maximum
double maximum = myArray.Max();
Console.WriteLine("The maximum value in the array is: " + maximum);
//Minimum
double minimum = myArray.Min();
Console.WriteLine("The minimum value in the array is: " + minimum);
//Mean
double mean = sum / myArray.Length;
Console.WriteLine("The mean average of the array is: " + mean);
}
//This method will exit the program
public static void exitProgram()
{
Environment.Exit(0);
}
}
}
does my findData() method look ok?
Your findData() method does acutally nothing.
Here is one approach
public static void findData()
{
Console.WriteLine("Find a number");
string myChoice = Console.ReadLine();
double number = -1;
if(!Double.TryParse(myChoice, out number))
{
Console.WriteLine("Invalid number");
}
else if (Array.IndexOf<double>(myArray, number) == -1)
{
Console.WriteLine("Number does not exist");
}
else
{
Console.WriteLine("Number does exist");
}
}
This should solve your add problem
public static void addData()
{
for (int i = 0; i < myArray.Length; i++)
{
bool success = false;
while (!success)
{
Console.WriteLine("Enter a number you would like to add");
string input = Console.ReadLine();
double number;
if (Double.TryParse(input, out number))
{
success = true;
myArray[i] = number;
}
else
{
Console.WriteLine("Invalid input. Please enter a valid number")
}
}
}
}
Your addData method doesn't make much sense: you first insert a double value into array and then you check if that value is a double (and it certainly is, because the array is of type double and can contain values only of that type).
Also, the Convert.ToDouble may throw exception if the user input is not valid. But I see you get the point of using Double.TryParse method, which returns true if the string (first parameter) is a valid number. So your addData method should look something like this:
//This method will add numbers to the array
public static void addData()
{
double number;
for (int i = 0; i < myArray.Length; i++)
{
Console.WriteLine("Enter a number you would like to add");
// read user input
string input = Console.ReadLine();
// condition is true if user input is a number
if (double.TryParse(input, out number))
myArray[i] = number;
else
Console.WriteLine("Invalid input. Please enter a valid number");
}
}
To find a number in your array you can use LINQ Contains extension method which does exacly that: it returns true if array contains element, otherwise false:
//This method will find a specific number within the array and check if it has already been entered
public static void findData()
{
double number;
Console.WriteLine("Find a number");
string input = Console.ReadLine();
// we use the same logic here as in the addData method to make sure the user input is a number
if (!double.TryParse(input, out number))
{
bool found = myArray.Contains(number);
if (found)
Console.WriteLine("Array has number {0}", number);
else
Console.WriteLine("Array doesn't have number {0}", number);
}
else
{
Console.WriteLine("Invalid input. Please enter a valid number");
}
}
Related
Having problem with my work i want to write a program that does the sum and average the student grade in the average function i used a do while loop since i want anyone to enter grade until the user enter -1 the loop end.
The problem is i do not want to run the _cal = Int32.Parse(Console.ReadLine()); in the fucntion instead run it in the main by passing a value to Average() parameter then using the value in main as a console.readlIne because i will use the user input to divide by the sum in order to get average am new to programming.
public static void Main()
{
Console.WriteLine("Please Enter the scores of your student: ");
Console.WriteLine("----------------------------------------");
_studentTotalGrade = Average();
Console.WriteLine("sum " + Sum);
Console.ReadLine();
}
public static double Average()
{
double _cal,_sumTotal = 0;
int i = 0;
do
{
_cal = Int32.Parse(Console.ReadLine());
if (_cal == -1)
{
break;
}
if (_cal > 20)
{
Console.WriteLine("Adjust score\");
continue;
}
_sumTotal +=_cal;
i--;
} while (_cal > i);
return _sumTotal;
}
}
So I have this very simple program that I have created that gets the user input and then pass the values to the method named average. Everything is perfectly fine, however, something crossed my mind like "What if the user only enters two numbers or an array of numbers?". I know that I have to use array as a parameter, but somehow I am not sure how to accomplish what i want to do. Do you guys have any tips on how I can achieve what i am trying to do? My code is here:
using System;
namespace Averages
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter number(s): ");
double num1 = Convert.ToInt32(Console.ReadLine());
double num2 = Convert.ToInt32(Console.ReadLine());
double num3 = Convert.ToInt32(Console.ReadLine());
average(num1, num2, num3);
Console.ReadKey();
}
static void average(double num1, double num2, double num3)
{
double avg = (num1 + num2 + num3) / 3;
Console.WriteLine("You have entered: " + num1 + ", " + num2 + ", " + num3);
Console.WriteLine("The average is: " + avg);
}
}
}
I would appreciate any help. Thank you!
you can ask user for input of comma delimited numbers. Or, you can repeat input until user enters something like 0. I that case, you can change your program into this:
using System;
using System.Collections.Generic;
using System.Linq;
namespace Averages
{
class Program
{
static void Main(string[] args)
{
//list to hold your numbers, way more flexible than array
List<double> enteredNubers = new List<double>();
//message user
Console.WriteLine("Enter number(s) or 0 to end: ");
//run this block of code indefinitely
while (true)
{
//take user input
string userinput = Console.ReadLine().Trim();
//if user enters 0, exit this loop
if (userinput == "0")
break;
double num;
//try to convert text to number
if (double.TryParse(userinput, out num))
{
//if it is successful, add number to list
enteredNubers.Add(num);
}
else //else message user with error
Console.WriteLine("Wrong input. Please enter number or 0 to end");
}
//when loop is exited (when user entered 0), call method that calculates average
Average(enteredNubers);
Console.ReadKey();
}
static void Average(List<double> numbers)
{
double sum = 0;
//go through list and add each number to sum
foreach (double num in numbers)
{
sum += num;
}
//or, you can sum it using linq like this:
//sum = numbers.Sum();
//or you can even calculate average by calling Average method on list, like numbers. Average();
//show message - all the entered numbers, separated by comma
Console.WriteLine("You have entered: " + string.Join(", ", numbers.ToArray()));
//write average
Console.WriteLine("The average is: " + sum/numbers.Count);
}
}
}
Let's solve the problem step by step. First we want to add a single double:
private static bool ReadDouble(out double value) {
value = 0.0;
while (true) {
Console.WriteLine("Enter number or X to exit:");
string input = Console.ReadLine().Trim();
if (input == "X" || input == "x")
return false;
else if (double.TryParse(input, out value))
return true;
Console.Write("Syntax error, please, try again.");
}
}
Now we are ready to read arbitrary number of values. Since we don't know the number, List<double> is a better choice than double[]
using System.Collections.Generic;
...
private static List<double> ReadDoubles() {
List<double> result = new List<double>();
while (ReadDouble(out var value))
result.Add(value);
return result;
}
Finally, we want to compute average
static void Main(string[] args) {
List<double> list = ReadDoubles();
if (list.Count <= 0)
Console.WriteLine("Empty list: no average");
else {
double sum = 0.0;
foreach (double item in list)
sum += item;
double avg = sum / list.Count;
Console.Write("The average is: " + avg);
}
}
However, you can do it in just few lines via Linq:
using System.Collections.Generic;
using System.Collections.Linq;
...
static void Main(string[] args) {
Console.WriteLine("Enter numbers separated by spaces, e.g. 1 2 3 15");
double avg = Console
.ReadLine()
.Split(new char[] { ' '}, StringSplitOptions.RemoveEmptyEntries)
.Select(item => double.Parse(item))
.Average();
Console.Write($"The average is: {avg}");
}
Here Update your methods Accordingly
static void Main(string[] args)
{
Console.WriteLine("Type Exit to stop the program... \nEnter number");
List<double> doubleList = new List<double>();
string input = Console.ReadLine();
double d;
while(!input.Equals("Exit"))
{
if(String.IsNullOrEmpty(input) || !Double.TryParse(input,out d))
{
break;
}
doubleList.Add(d);
input = Console.ReadLine();
}
average(doubleList);
Console.ReadKey();
}
static void average(List<double> doubleData)
{
double total = 0;
foreach (double number in doubleData)
{
total += number;
}
Console.WriteLine("Average = " + total/doubleData.Count);
}
Something like the following should meet your needs:
string stopLine = "STOP";
List<double> lines = new List<double>();
string line;
while ((line = Console.ReadLine()) != stopLine) {
lines.Add(Convert.ToDouble(line));
}
Average(lines);
Console.ReadLine();
Now your average method becomes
private static void Average(List<double> lines) {
Console.WriteLine(lines.Average());
}
Note that you should handle the case where the input is not a number.
static void Main(string[] args)
{
Console.WriteLine("Enter number(s): ");
string input = "";
List<double> doubleList = new List<double>();
while (input != "q")
{
input = Console.ReadLine();
if(input != "q")
{
try
{
doubleList.Add(Convert.ToInt32(input));
}
catch
{
Console.WriteLine("Invalid input");
}
}
}
average(doubleList);
Console.ReadKey();
}
static void average(List<double> myList)
{
double sum = 0;
Console.Write("You have entered: ")
foreach (int element in myList)
{
sum += element;
Console.Write(element + ", ");
}
Console.WriteLine("");
double avg = sum / myList.Count;
Console.WriteLine("The average is: " + avg);
}
static void Main(string[] args)
{
var numbers = new List<double>();
Console.WriteLine("Enter the three numbers, one per line");
for (var i = 0; i < 3; ++i)
{
while (true)
{
if (double.TryParse(Console.ReadLine(), out var enteredNumber))
{
//the number is a number, so...
numbers.Add(enteredNumber);
break;
}
//if not a number...
Console.WriteLine("That's not a number, try again");
}
}
Average(numbers);
Console.ReadKey();
}
static void Average(IEnumerable<double> numbers)
{
var average = numbers.Average();
Console.Write("You have entered: ");
foreach (var num in numbers)
{
Console.Write($" {num} ");
}
Console.WriteLine(String.Empty);
Console.WriteLine("The average is: " + average);
}
In general, Lists are better than Arrays for this kind of thing; List's are stretchy, Arrays are not. If you want this to work with 4 (or 200) numbers, all you have to do is change the for loop's bounds.
I'm using double.TryParse, this way I can let the user correct a badly entered number (always assume users will enter bad data). I'm passing the collection of numbers to the average function as an IEnumerable and not a List (the Average function is hardly needed (note that the calculation of the average is just an extension method on collections of numerics) but you had one, so I included it. An IEnumerable cannot be changed by the called function, so it's more appropriate here (and, all lists (and all arrays, for that matter) are enumerable).
Looking at all these fancy answers,i guess people are forgetting the basics of programming.
The OP literally states using arrays and instead of that you all are pushing him into hard to read code. The guy is trying to learn the basics which obviously no one cares to learn about.
Dear Cyrus don't get into generics right away. I would suggest that you stick to arrays for a while.
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter number(s): ");
double[] values = new double[3]; //initialize double array with its size
for (int i = 0; i < values.Length; i++)
{
//iterate through the array and assign value to each index of it.
values[i]=Convert.ToDouble(Console.ReadLine());
}
average(values);
Console.ReadKey();
}
//set method that accepts double array as parameter
static void average(double[] values)
{
double average =0;// declare var that will hold the sum of numbers
int length = values.Length;//get array length, use it to divide the summation of numbers
Console.WriteLine("You have entered: ");
for (int i = 0; i < values.Length; i++)
{
//also display the numbers if you need to
Console.WriteLine(values[i]);
//iterate through each value in the array and sum it up.
average = values[i] + average;
}
//divide the sum of numbers by the length of array
Console.WriteLine("The average is: " + (average/length));
}
}
You can also dynamically set the length of the array by letting the user input its length, just play with code and let your imagination loose. Happy coding!
You have a couple options. Either ask for the user input to be delimited somehow. For example a comma delimited user input would be"1, 2, 3, 4". You've then got to worry about parsing that and ensuring the user entered valid input.
Another option is to have a while loop that has Console.ReadLine() within, and you only exit the loop when the user enters a pre-determined exit word (such as "stop" or exit")
static void Main(string[] args)
{
var inputValues = new List<double>();
while (true)
{
var input = Console.ReadLine();
if (input.Equals("stop", StringComparison.InvariantCultureIgnoreCase))
break;
if (double.TryParse(input, out double inputValue))
{
inputValues.Add(inputValue);
}
else
{
Console.WriteLine("Invalid input!");
}
}
PrintAverage(inputValues);
Console.ReadKey();
}
static void PrintAverage(IEnumerable<double> values)
{
Console.WriteLine("You have entered: {0}", string.Join(", ", values));
Console.WriteLine("The average is: {0}", values.Average());
}
Here I've opted for the second option. It'll continuously loop until the input is stop. It will also now try parse the value rather than directly convert, and will print a warning message if the parse failed.
If the parse was successful it's added to our inputValues collection. Once out of the while loop, we pass the collection to PrintAverage - a method that takes an IEnumerable<double> (could be one value, 100 values, or no values). Because List implements IEnumerable, we can pass our list to this method. IEnumerable has an Average() method built-in.
I'm new to c# and am trying to make a simple calculator.
It works fine until it goes back to the start to take a new number.
When taking the new number it says it cant convert the user input to a integer.
using System;
namespace simpleCalculator
{
class MainClass
{
public static void Main(string[] args)
{
start:
Console.Clear();
Console.WriteLine("Enter first number");
int x = Convert.ToConsole.ReadLine();
Console.WriteLine("Would you like to\n1. Add\n2. Multiply\n3. Devide");
string o = Console.ReadLine();
if (o == "1")
{
Console.WriteLine("Enter second number\n");
int y = Convert.ToInt32(Console.ReadLine());
add(temp, y);
goto start;
Console.Clear();
goto start;
}
}
public static void add(int num01, int num02)
{
Console.Clear();
Console.WriteLine((num01 + num02) + "\nPress enter to contiue.");
Console.Read();
}
}
}
Use TryParse so if the parsing fails, you will not get an exception.
var enteredValue = Console.ReadLine();
var parsedValue;
if (!int.TryParse(enteredValue, out parsedValue))
{
// parse failed do whatever you want
}
Do that for both entries and if both of them pass, then call your add method.
You're looking for int.Parse(). Be careful to validate your input. You should probably create an escape condition.
Edited to show an alternative solution
Edited to be more explicit on how to handle some input
class Program
{
public static void Main(string[] args)
{
string input = String.Empty;
int x = 0, y = 0;
while (true)
{
try
{
Console.WriteLine("Enter first number");
x = int.Parse(Console.ReadLine());
Console.WriteLine("Would you like to\n1. Add\n2. Multiply\n3. Divide");
input = Console.ReadLine();
Console.WriteLine("Please enter a second number");
y = int.Parse(Console.ReadLine());
}
catch
{
Console.WriteLine("Invalid input");
continue;
}
switch (input)
{
case "1":
Console.WriteLine($"{x} + {y} = " + add(x, y));
break;
case "2":
//TODO implement multiply case
break;
case "3":
//TODO implement divide case
break;
default:
Console.WriteLine("Invalid input");
break;
}
}
}
public static int add(int x, int y) => x + y;
}
Try this:
int numbers = Convert.ToInt32("1234");
here i ask the user for homework scores which are then averaged after discarding the smallest and largest score. i have stored the user input in an array. in my DisplayResults method im not sure how to display the lowest and highest scores that were discarded. any help is appreciated! Here is what i have so far:
class Scores
{
static void Main(string[] args)
{
double sum = 0;
double average = 0;
int arraySize;
double[] inputValues;
arraySize = HowManyScores();
inputValues = new double[arraySize];
GetScores(inputValues);
sum = CalculateSum(inputValues);
average = CaculateAverage(sum, arraySize);
DisplayResults(inputValues, average);
Console.Read();
}
public static int HowManyScores()
{
string input;
int size;
Console.WriteLine("How many homework scores would you like to enter?");
input = Console.ReadLine();
while (int.TryParse(input, out size) == false)
{
Console.WriteLine("Invalid data. Please enter a numeric value.");
input = Console.ReadLine();
}
return size;
}
public static void GetScores(double[] inputValues)
{
double scoreInput;
Console.Clear();
for (int i = 0; i < inputValues.Length; i++)
{
scoreInput = PromptForScore(i + 1);
inputValues[i] = scoreInput;
}
}
public static double PromptForScore(int j)
{
string input;
double scoreInput;
Console.WriteLine("Enter homework score #{0}:", j);
input = Console.ReadLine();
while (double.TryParse(input, out scoreInput) == false)
{
Console.WriteLine("Invalid Data. Your homework score must be a numerical value.");
input = Console.ReadLine();
}
while (scoreInput < 0)
{
Console.WriteLine("Invalid Data. Your homework score must be between 0 and 10.");
input = Console.ReadLine();
}
while (scoreInput > 10)
{
Console.WriteLine("Invalid Data. Your homework score must be between 0 and 10.");
input = Console.ReadLine();
}
return scoreInput;
}
public static double CalculateSum(double[] inputValues)
{
double sum = 0;
for (int i = 1; i < inputValues.Length - 1; i++)
{
sum += inputValues[i];
}
return sum;
}
public static double CaculateAverage(double sum, int size)
{
double average;
average = sum / ((double)size - 2);
return average;
}
public static void DisplayResults(double[] inputValues, double average)
{
Console.Clear();
Console.WriteLine("Average homework score: {0}", average);
//Console.WriteLine("Lowest score that was discarded: {0}",
//Console.WriteLine("Highest score that was discarded: {0}",
}
}
}
You basically only have to do one thing: Sorting the array after you received your input data. Then, printing the first and last value gives you the minimal and maximal score. Use
Array.Sort(intArray);
in main after calling GetScores and
Console.WriteLine("Lowest score: {0} Highest score: {1}",
inputValues[0], inputValues[inputValues.Length - 1]);
to print the results. Cheers
EDIT: The proposal by Jens from the comments using the Min/Max is probably more what you're looking for if you're not interested in complete ordering of your values.
I would like my program to fill an array with user input, but with an numeric input (then program will make specific calculations with that numbers, but it's not important for now).
If no input is done, program should stop reading numbers and print it. I have a couple of errors, especially in case of parsing, because I have tried a couple of solutions, and I have no idea in which part of code and maybe what way, numbers in an array should be parsed to avoid receiving an "cannot implicitly convert type string to int" or "cannot implicitly convert type int[] to int".
This how my code looks like:
public static void Main (string[] args)
{
int[] userInput = new int[100];
int xuserInput = int.Parse (userInput);
for (int i = 0; i<userInput.Length; i++)
{
userInput[i] = Console.ReadLine ();
if (userInput == "")
break;
}
Console.WriteLine (userInput);
}
you should take the input to a string and try to parse it to integer:
public static void Main(string[] args)
{
int[] userInput = new int[100];
int counter = 0;
for (counter = 0; counter < userInput.Length; counter++)
{
string input = Console.ReadLine();
if (input == "")
break;
else
int.TryParse(input, out userInput[counter]);
}
for (int i = 0; i < counter; i++)
{
Console.WriteLine(userInput[i]);
}
Console.ReadLine();
}
try parse will not throw exception like parse will.
if you decide to use parse, catch exceptions
Try this:
int[] userInputs = new int[100];
int parsedInput;
int inputs = 0;
bool stop = false;
while (inputs < 100 && !stop)
{
string userInput = Console.ReadLine();
if (userInput == "")
{
stop = true;
}
else if (Int32.TryParse(userInput, out parsedInput))
{
userInputs[i] = parsedInput;
inputs++;
}
else
{
Console.WriteLine("Please enter a number only!");
}
}
for each (int number in userInputs)
{
Console.WrietLine(number.ToString());
}
This code does a few things.
First, a while loop is used to ensure the user inputs 100 numbers or doesn't enter any data.
Next, it gets the input from the user. If it's an empty input, it sets the stop flag to true, which will exit the loop.
If the input wasn't empty, it uses TryParse to determine if the input is a number. If it is, it returns true and the converted input is added to the array and the counter incremented.
If the parse fails, the user is prompted to enter a number.
Once the array is filled, it loops through the array and prints out each input.
The problem is that you are parsing userInput which is an array with int.Parse instead of parsing the input you got by Console.ReadLine()
int xuserInput = int.Parse (userInput); // Remove this statement.
For parsing user input you need to parse like this
string input = Console.ReadLine ();
if (input == "")
break;
else
int.TryParse(input, out userInput[i]);
try this.
public static void Main (string[] args)
{
int[] userInput = new int[100];
int xuserInput = int.Parse (userInput);
for (int i = 0; i<userInput.Length; i++)
{
int temp = int.Parse(Console.ReadLine());
userInput[i] = temp;
if (userInput == "")
break;
}
Console.WriteLine (userInput);
}
You just might want to use this
static void Main(string[] args)
{
int[] userInput = new int[100];
string recievedInput = "";
for (int i = 0; i<userInput.Length; i++)
{
recievedInput = Console.ReadLine();
int.TryParse(recievedInput, out userInput[i]);
if (recievedInput == "")
break;
}
Console.WriteLine (userInput); //this will only print the type name of Userinput not all element
}
The following program reads numbers from user.
If user enters an invalid number, then it reports with the message: Not a valid number.
If user enters nothing, then the program prints all the numbers entered by the user.
class Program
{
static void Main(string[] args)
{
int[] userInput = new int[10];
for(int count = 0; count <= 9; count++)
{
int number;
string input = Console.ReadLine();
bool result = Int32.TryParse(input, out number);
if (result)
{
userInput[count] = number;
}
else if (!result)
{
if (input != string.Empty)
Console.WriteLine("Not a valid number.");
else if (input.Equals(string.Empty))
{
foreach (var item in userInput)
{
Console.WriteLine(item.ToString());
}
Console.WriteLine("Press any key to continue...");
Console.ReadKey(true);
return;
}
}
}
}
}
Please let me know, if this is okay to you.