Hi I'm having trouble with an error "No overload method 'conversationOutput' takes '2' arguments" please help. I'm having a little trouble understanding method calling, and calling variables from main().
class MainClass
{
static void Main ()
{
string selection;
double values;
selection = userChoice();
values = userInput(selection);
conversationOutput(selection, values);
}
static string userChoice ()
{
string choose;
Console.WriteLine("Welcome to the OHM's law calculator! \n \nWhat would you like to calcualte?");
Console.WriteLine("1. Voltage:");
Console.WriteLine("2. Current:");
Console.WriteLine("3. Resistance:");
do
{
choose = Console.ReadLine();
if (choose != "1" && choose != "2" && choose != "3")
{
Console.WriteLine("Please only select '1' for voltage, '2' for current, '3' resistance");
}
} while (choose != "1" && choose != "2" && choose != "3");
switch (choose)
{
case "1":
Console.Write("You have choose to calculate Voltage.\n");
break;
case "2":
Console.Write("You have choose to calculate Current.\n");
break;
case "3":
Console.WriteLine("You have choose to calculate Resistance.\n");
break;
}
return choose;
}
static double userInput (string choose)
{
double voltageD = 0.0;
double currentD = 0.0;
double resistanceD = 0.0;
string current;
string voltage;
string resistance;
bool ok = true;
do if (choose != "1")
{
do
{
Console.WriteLine("Please enter your value for Voltage (volts)...");
voltage = Console.ReadLine();
ok = double.TryParse(voltage, out voltageD);
if (!ok)
{
Console.WriteLine("Please Enter a NUMERICALE VALUE ONLY");
}
} while (!ok);
if (voltageD < 0)
{
Console.WriteLine("Please select a number larger than the lower limit of 0 volts");
}
} while (voltageD < 0);
do if (choose != "2")
{
do
{
Console.WriteLine("Please enter your value for Current (amp)...");
current = Console.ReadLine();
ok = double.TryParse(current, out currentD);
if (!ok)
{
Console.WriteLine("Please Enter a NUMERICALE VALUE ONLY");
}
} while (!ok);
if (currentD < 0.01)
{
Console.WriteLine("Please select a number larger than the lower limit of 0.01 amp");
}
} while (currentD < 0.01);
do if (choose != "3")
{
do
{
Console.WriteLine("Please enter your value for Resistance (ohm)...");
resistance = Console.ReadLine();
ok = double.TryParse(resistance, out resistanceD);
if (!ok)
{
Console.WriteLine("Please Enter a NUMERICALE VALUE ONLY");
}
} while (!ok);
if (resistanceD < 10)
{
Console.WriteLine("Please select a number larger than the lower limit of 10 ohm");
}
} while (resistanceD < 10);
return 0;
}
static double conversationOutput (string choose, double currentD, double voltageD, double resistanceD)
{
/* v = i*r */
double output = 0.0;
string units = "";
if (choose == "1")
{
output = (currentD) * (resistanceD);
units = "Volts";
}
if (choose == "2")
{
output = (voltageD) / (resistanceD);
units = "Amps";
}
if (choose == "3")
{
output = (voltageD) / (resistanceD);
units = "OHM";
}
Console.WriteLine("The calculated value is {0:F3} {1:F3}", output, units);
return 0;
}
}
The reason is you have a method
double conversationOutput (string choose, double currentD, double voltageD, double resistanceD)
which has 4 parameters and you are passing only 2 parameters to the method.
define the missing parameters as optional
static double conversationOutput (string choose, double currentD, double voltageD =0, double resistanceD =1)
As per the method definition, conversationOutput expects four parameters.
static double conversationOutput (string choose, double currentD, double voltageD, double resistanceD) {}
But you are calling it by passing just two parameters.
conversationOutput(selection, values);
That's why you are getting such error.
It will work if you call the conversationOutput method by passing four parameters.
Related
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");
}
}
I am trying to continuously ask user for a number between 300-850. When the user enters a valid number, add it to the total and ask again. If the number is invalid, display an error. Before program ends, display the average of total number by amount of times of input. End program if user enters a sentinel value. I don't know how to check if user enters a sentinel value.
using System;
class CreditScores
{
static void Main()
{
var iterations = 0;
double total = 0;
int sum = 0;
double average = 0;
int count = 0;
Console.WriteLine("Enter value between 300 to 850.");
int first = int.Parse(Console.ReadLine());
//trying to get it to stop when sentinel value reached.
while (iterations < 1000)
{
iterations++;
Console.WriteLine("Enter value between 300 to 850.");
int input = int.Parse(Console.ReadLine());
//not sure how to check if input is a number or not
if(input == integer)
{
if( input < 850 && input > 300 )
{
total +=input;
}
}
else
{
break;
}
}
total = sum + total;
Console.WriteLine("Total is {0}", total);
average = total / count;
Console.WriteLine("The average is {0}", average);
}
}
Modification/fix of Your Method
Also, I would read all the way to the end for the more robust method you could use.
First thing I would change:
while (iterations < 1000)
{
...
}
To this (which we are not done yet, read to the end):
while (input != "calculate") // or some other string
{
...
}
Then, before the while starts, make input a string.
string input = "";
while (input != "calculate") // or some other string
{
...
}
Now, we declared an input variable that is already an int later on. Let's fix that.
Console.WriteLine("Enter value between 300 to 850.");
input = Console.ReadLine();
int value = 0;
if (int.TryParse(input, out value))
{
// Clearly it's a valid integer at this point
if (value < 850 && value > 300)
{
total += value;
}
}
else
{
// Wasn't a number, might be our sentinel.
if (input == "calculate")
break;
else
{
// Throw an error or something.
}
}
Now, we need to put it together and do some cleaning.
int total = 0;
int numbersEntered = 0;
string input = "";
while (input != "calculate")
{
Console.WriteLine("Enter value between 300 to 850.");
input = Console.ReadLine();
int value = 0;
if (int.TryParse(input, out value))
{
// Clearly it's a valid integer at this point
if (value < 850 && value > 300)
{
total += value;
numbersEntered++;
}
}
else
{
// Wasn't a number, might be our sentinel.
if (input == "calculate")
break;
else
{
// Throw an error or something.
}
}
}
Console.WriteLine("Total is {0}", total);
double average = (double)total / numbersEntered;
Console.WriteLine("The average is {0}", average);
(I know, long answer. But it should help you step through the problem in the future. Also, I wrote this all by memory, I can't guarantee it will compile.)
Update: just tested it, works as expected.
A more Robust Method
Lastly, and this is really the coolest method in my opinion, use a List<int> and some extension methods.
List<int> values = new List<int>();
string input = "";
while (input != "calculate")
{
Console.WriteLine("Enter value between 300 to 850.");
input = Console.ReadLine();
int value = 0;
if (int.TryParse(input, out value))
// Clearly it's a valid integer at this point
if (value < 850 && value > 300)
values.Add(value);
else
{
// Was outside our range
}
else
// Wasn't a number, might be our sentinel.
if (input == "calculate")
break;
else
{
// Throw an error or something.
}
}
Console.WriteLine("Total is {0}", values.Sum());
Console.WriteLine("The average is {0}", values.Average());
Advantages to this method? It saves a list of the values entered, allowing you to do more with them that you cannot do with the method you currently have. It also uses the int.Sum() and int.Average() extension methods rather than your own math.
What is this int.TryParse(string, out int) sorcery?
The int.TryParse(string, out int) method (as defined by MSDN) will take an input string, and return a boolean value that indicates if it would make a valid int structure or not.
In the case that the string is a valid int, then the int parameter is filled with the integer representation of the string.
I.e.:
string myString = "100";
int value = 0;
if (int.TryParse(myString, out value))
Console.WriteLine("myString was a valid int: {0}", value);
else
Console.WriteLine("myString was not a valid int.");
This version will return true and print: myString was a valid int: 100.
Example 2:
string myString = "blah";
int value = 0;
if (int.TryParse(myString, out value))
Console.WriteLine("myString was a valid int: {0}", value);
else
Console.WriteLine("myString was not a valid int.");
This version will return false, and print myString was not a valid int.. The value variable would also be 0.
Warning:
When using int.TryParse(string input, out int value), do not rely on the value parameter as 0 to indicate failure. If the input is "0", then the value will also be 0, and the method will return true.
You want to set the condition of your while loop to something that a user can trigger as false (the sentinel).
Then put a for loop inside that if you want to do a set number of iterations, for loops are better for situations where you know how many iterations you're doing.
BUT if you want to stick to while loops only, here's a quick code snippet you could use:
while (input != 0 && iterations < 1000) //or some sentinel value you choose
{
//Your logic here, now the loop will quit if if the user enters 0
//OR you run out of iterations
}
using System;
class CreditScores
{
static void Main()
{
double total = 0;
int sum = 0;
int count = 0;
Console.WriteLine("Enter value between 300 to 850.");
int first = int.Parse(Console.ReadLine());
//trying to get it to stop when sentihel value reached.
for (iterations = 0; iterations < 1000; iterations++)
{
Console.WriteLine("Enter value between 300 to 850.");
int input;
// Check number is integer
if (int.TryParse(Console.ReadLine(), out input)
{
if(input > 300 && input < 850)
{
total +=input;
}
}
else
{
break;
}
count++;
}
total = sum + total;
Console.WriteLine("Total is {0}", total);
double average = total/count;
Console.WriteLine("The average is {0}", average);
Console.ReadLine(); // Either this or run with Ctrl-F5
}
}
The behaviour would be to add the totals until the user entered something that couldn't be parsed, and then exit.
Does this work?
string sentinalValue = "done";
string input = "";
while (iterations < 1000 && input != sentinalValue)
{
iterations++;
Console.WriteLine("Enter value between 300 to 850.");
input = Console.ReadLine();
int value;
if (int.TryParse(input, out value))
{
if( value < 850 && value > 300 )
{
total +=input;
}
}
else
{
Console.WriteLine("That is not a number!");
}
}
Console.WriteLine("Enter the cost of the item");
string input = Console.ReadLine();
double price = Convert.ToDouble(input);
Hello, I want the keyboard buttons, A-Z, brackets, question mark, etc to be disabled. I want it so if you type it in, it will not show up in the Console. I only want the numbers 1-9 to show up. This is in C# Console application. Thanks for the help!
try this code snippet
string _val = "";
Console.Write("Enter your value: ");
ConsoleKeyInfo key;
do
{
key = Console.ReadKey(true);
if (key.Key != ConsoleKey.Backspace)
{
double val = 0;
bool _x = double.TryParse(key.KeyChar.ToString(), out val);
if (_x)
{
_val += key.KeyChar;
Console.Write(key.KeyChar);
}
}
else
{
if (key.Key == ConsoleKey.Backspace && _val.Length > 0)
{
_val = _val.Substring(0, (_val.Length - 1));
Console.Write("\b \b");
}
}
}
// Stops Receving Keys Once Enter is Pressed
while (key.Key != ConsoleKey.Enter);
Console.WriteLine();
Console.WriteLine("The Value You entered is : " + _val);
Console.ReadKey();
This MSDN article explains how to read characters one at a time in a console window. Test each character as it is input with the Char.IsNumber() method, and reject those characters that fail the test.
In a while, I got a solution really short:
double number;
Console.Write("Enter the cost of the item: ");
while (!double.TryParse(Console.ReadLine(), out number))
{
Console.Write("This is not valid input. Please enter an integer value: ");
}
Console.Write("The item cost is: {0}", number);
See you!
Here is one approach. It's probably overkill if you're just starting out in C#, since it uses some more advanced aspects of the language. In any case, I hope you find it interesting.
It has some nice features:
The ReadKeys method takes an arbitrary function for testing whether the string so far is valid. This makes it easy to reuse whenever you want filtered input from the keyboard (e.g. letters or numbers but no punctuation).
It should handle anything you throw at it that can be interpreted as a double, e.g. "-123.4E77".
However, unlike John Woo's answer it doesn't handle backspaces.
Here is the code:
using System;
public static class ConsoleExtensions
{
public static void Main()
{
string entry = ConsoleExtensions.ReadKeys(
s => { StringToDouble(s) /* might throw */; return true; });
double result = StringToDouble(entry);
Console.WriteLine();
Console.WriteLine("Result was {0}", result);
}
public static double StringToDouble(string s)
{
try
{
return double.Parse(s);
}
catch (FormatException)
{
// handle trailing E and +/- signs
return double.Parse(s + '0');
}
// anything else will be thrown as an exception
}
public static string ReadKeys(Predicate<string> check)
{
string valid = string.Empty;
while (true)
{
ConsoleKeyInfo key = Console.ReadKey(true);
if (key.Key == ConsoleKey.Enter)
{
return valid;
}
bool isValid = false;
char keyChar = key.KeyChar;
string candidate = valid + keyChar;
try
{
isValid = check(candidate);
}
catch (Exception)
{
// if this raises any sort of exception then the key wasn't valid
// one of the rare cases when catching Exception is reasonable
// (since we really don't care what type it was)
}
if (isValid)
{
Console.Write(keyChar);
valid = candidate;
}
}
}
}
You also could implement an IsStringOrDouble function that returns false instead of throwing an exception, but I leave that as an exercise.
Another way this could be extended would be for ReadKeys to take two Predicate<string> parameters: one to determine whether the substring represented the start of a valid entry and one the second to say whether it was complete. In that way we could allow keypresses to contribute, but disallow the Enter key until entry was complete. This would be useful for things like password entry where you want to ensure a certain strength, or for "yes"/"no" entry.
This code will allow you to:
Write only one dot (because numbers can have only one decimal separator);
One minus at the begining;
One zero at the begining.
It means that you not be able to write something like: "00000.5" or "0000...-5".
class Program
{
static string backValue = "";
static double value;
static ConsoleKeyInfo inputKey;
static void Main(string[] args)
{
Console.Title = "";
Console.Write("Enter your value: ");
do
{
inputKey = Console.ReadKey(true);
if (char.IsDigit(inputKey.KeyChar))
{
if (inputKey.KeyChar == '0')
{
if (!backValue.StartsWith("0") || backValue.Contains('.'))
Write();
}
else
Write();
}
if (inputKey.KeyChar == '-' && backValue.Length == 0 ||
inputKey.KeyChar == '.' && !backValue.Contains(inputKey.KeyChar) &&
backValue.Length > 0)
Write();
if (inputKey.Key == ConsoleKey.Backspace && backValue.Length > 0)
{
backValue = backValue.Substring(0, backValue.Length - 1);
Console.Write("\b \b");
}
} while (inputKey.Key != ConsoleKey.Enter); //Loop until Enter key not pressed
if (double.TryParse(backValue, out value))
Console.Write("\n{0}^2 = {1}", value, Math.Pow(value, 2));
Console.ReadKey();
}
static void Write()
{
backValue += inputKey.KeyChar;
Console.Write(inputKey.KeyChar);
}
}
You can do it with a single line code as follows:
int n;
Console.WriteLine("Enter a number: ");
while (!int.TryParse(Console.ReadLine(), out n)) Console.WriteLine("Integers only allowed."); // This line will do the trick
Console.WriteLine($"The number is {n}");
You can change int into double in case you wanted to allow double instead of integers and so on.
string input;
double price;
bool result = false;
while ( result == false )
{
Console.Write ("\n Enter the cost of the item : ");
input = Console.ReadLine ();
result = double.TryParse (input, out price);
if ( result == false )
{
Console.Write ("\n Please Enter Numbers Only.");
}
else
{
Console.Write ("\n cost of the item : {0} \n ", price);
break;
}
}
I'm new to C# and I have encountered some problems with my console application that I'm recently working on. I am trying to have 3 methods:
getsales to get the sales the user made, calcCom to calculate the commission for the sales and finally main to make them work and establish the program.
I'm having trouble to make those methods work with(in) each other.
After i entered all the sales, the program goes to the else-statement and tells me "invalid entry". Since i haven't really gotten to output the variables I didn't expect any kind of output, but I want the program to tell the user the commission and sale for each person.
Please excuse me if I misused any terms or words, like I said I am new to this language! :D
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication38
{
class Program
{
public static void getsales ()
{
string inputsales;
double total = 0;
double sale = 0;
for (int salecount = 1; salecount <= 3; ++salecount)
{
Console.WriteLine("Enter sale: ");
inputsales = Console.ReadLine();
sale = Convert.ToDouble(inputsales);
total = total + sale;
Console.WriteLine();
}
}
public static void calcComm ()
{
double total = 0;
double comm = 0;
comm = total * 0.2;
}
static void Main()
{
Console.WriteLine(" Sunshine Hot Tubs \n Sales Commissions Report\n");
char Letter;
string name;
const string name1 = "Andreas";
const string name2 = "Brittany";
const string name3 = "Eric";
string inputLetter;
Console.WriteLine("Please enter intial or type z to quit");
inputLetter = Console.ReadLine();
Letter = Convert.ToChar(inputLetter);
while (Letter != 'z')
{
if (Letter == 'a')
{
name = name1;
getsales();
calcComm();
}
if (Letter == 'b')
{
name = name2;
getsales();
calcComm();
}
if (Letter == 'e')
{
name = name3;
getsales();
calcComm();
}
else
{
Console.WriteLine("Invalid entry try again");
inputLetter = Console.ReadLine();
}
}
}
}
}
I think your problem is you need this:
if (Letter == 'a')
{
name = name1;
getsales();
calcComm();
}
else if (Letter == 'b')
{
name = name2;
getsales();
calcComm();
}
else if (Letter == 'e')
{
name = name3;
getsales();
calcComm();
}
else
{
Console.WriteLine("Invalid entry try again");
inputLetter = Console.ReadLine();
}
You also need to copy this code after the else block, at the very end of your while loop.
Console.WriteLine("Please enter intial or type z to quit");
inputLetter = Console.ReadLine();
Letter = Convert.ToChar(inputLetter);
Also, remove this line from inside the else block. It isn't needed.
inputLetter = Console.ReadLine();
You probably intended to display the commision on the console. Change your getsales and calcComm to look like this:
public static void getsales ()
{
string inputsales;
double total = 0;
double sale = 0;
for (int salecount = 1; salecount <= 3; ++salecount)
{
Console.WriteLine("Enter sale: ");
inputsales = Console.ReadLine();
sale = Convert.ToDouble(inputsales);
total = total + sale;
Console.WriteLine();
}
calcComm(total);
}
public static void calcComm (double total)
{
double comm = 0;
comm = total * 0.2;
Console.WriteLine(comm);
}
Then remove all calls to calcComm from the Main method.
The variable "total" is in the two methods and they do not persist the data that you are looking for between the two methods that you have defined. That is, the total variable in getSales() method is different from calcComm() method.
You should move this:
double total = 0;
outside of the two methods and put it within the class with a static scope. Like:
class Program
{
static double total;
Also, reinitialize total to zero within your getSales() method.
calcComm() doesn't do anything...
I think you might want to have some of your variables as global so that if they are modified by a method you can still retrieve their value, or even better pass them to the method and get them returned with the new values.
To declare global variables you should declare them inside the class Program but outside any method and then make sure that no other methods have variables with the same name
Can someone tell me why this doesnt work. When I enter the loop it prints everything instead of one line and get the users input. It prints Enter the integer the account numberEnter the integer the account balanceEnter the account holder lastname
Got it working thanks everyone, but now the searchaccounts doesnt work
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class accounts
{
private int[] accountnum = new int[5]; //private accountnum array of five integer account numbers
private int[] accountbal = new int[5];//private balance array of five balance amounts
private string[] accountname = new string[5];//private accntname array to hold five last names
public void fillAccounts()
{
int bal;
int accountnumber;
string name;
for (int x = 0; x < 5; ++x)
{
Console.Write("Enter the integer the account number");
accountnumber = Console.Read();
Console.Write("Enter the integer the account balance");
bal = Console.Read();
Console.Write("Enter the account holder lastname");
name = Console.ReadLine();
accountnum[x] = accountnumber;
accountbal[x] = bal;
accountname[x] = name;
}
}
public void searchAccounts()
{
Console.WriteLine("Enter the account number");
int acctnum = Console.Read();
for (int x = 0; x < 6; ++x)
{
if (x < 5)
{
if (accountnum[x] == acctnum)
{
Console.WriteLine("Account #{0} has a balance of {1} for customer {2}", acctnum, accountbal[x].ToString("C"), accountname[x]);
break;
}
}
else
{
Console.WriteLine("You entered invalid account number");
}
}
}
public void averageAccounts()
{
int sum = 0;
int avg;
for (int x = 0; x < 5; ++x)
{
sum = accountbal[x] + sum;
}
avg = sum / 5;
Console.WriteLine("The average dollar amount is {0}", avg.ToString("c"));
}
}
class assignment3_alt
{
static void Main(string[] args)
{
accounts myclass = new accounts();
string userin;
myclass.fillAccounts();
int i = 0;
while (i != 1)
{//use the following menu:
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("*****************************************");
Console.Write("Enter option-->");
userin = Console.ReadLine();
if (userin == "a" || userin == "A")
{
myclass.searchAccounts();
}
else if (userin == "b" || userin == "B")
{
myclass.averageAccounts();
}
else if (userin == "x" || userin == "X")
{
break;
}
else
{
Console.WriteLine("You entered an invalid option");
}
}
}
}
}
Console.Read only reads a single character. You need to use Console.ReadLine.
Console.Write("Enter the integer the account number");
accountnumber = int.Parse(Console.ReadLine());
Console.Write("Enter the integer the account balance");
bal = int.Parse(Console.ReadLine());
Console.Write("Enter the account holder lastname");
name = Console.ReadLine();
You might also want to consider using int.TryParse instead of int.Parse so that you can better handle invalid input.
For your new question it is the same error. Just replace:
int acctnum = Console.Read();
with
int acctnum = int.Parse(Console.ReadLine());
or (preferably)
int acctnum;
if (!int.TryParse(Console.ReadLine(), out acctnum))
{
Console.WriteLine("You need to enter a number");
return;
}
The first will fail if the user doesn't enter a valid integer the second will print out a nice error message and return to the loop.
This is not an answer, as other have already put up some good ones. These are just a few tips about your code.
Instead of looping with while (i != 1), never changing the value of i and terminating the loop with break, it would be better to use a do-while loop, like this:
do
{
// blah blah
} while(userin != "x" || userin != "X")
It is less confusing than having a variable with no use at all.