C# user input int to array - c#

I'm asking the user to input 5 numbers and store it into an array so I can send the values in a method and subtract 5 numbers from each array. When I use the:
for(I=0;I<5;I++) {
int[] val = Console.ReadLine();}
It says I can't convert int[] to int. I'm a little rusty in my programming. I also don't know how to send the array values from the main to the method.

You're assigning the string input from the Console to an array of int. This is wrong for two reasons:
int arrays (int[]) are a collection of ints.
The value you're getting from the Console isn't an int and needs to be parsed first.
This is a slight diversion, but I also don't think you should be using an array. Arrays generally have significantly less function in C# than the built-in List<T>. (All the rockstars chime in here) Some people say there's no reason to use arrays at all - I won't go that far, but I think for this use case it'll be a lot easier to just add items to a List than to allocate 5 spaces and initialize values by index.
Either way, you should use int.TryParse(), not int.Parse(), given that you'll immediately get an exception if you don't check if the user input was parseable to int. So example code for taking in strings from the user would look like this:
List<int> userInts = new List<int>();
for (int i = 0; i < 5; i++)
{
string userValue = Console.ReadLine();
int userInt;
if (int.TryParse(userValue, out userInt))
{
userInts.Add(userInt);
}
}
If you'd still like to use the array, or if you have to, just replace List<int> userInts... with int[] userInts = new int[5];, and replace userInts.Add(userInt) with userInts[i] = userInt;.

You initialize the array first
int[] val = new int[5];
and then when you do a for loop:
for (int i=0; i<val.Length; i++)
{
val[i] = int.Parse(Console.ReadLine());
}
Hint: To send the array values from main to the method, just look at how static void main is formed:
static void Main(string[] args)
Meaning main is accepting a string array of of console arguments.

You just need to parse the string being entered from the console to int first.You accept int by doing:
for(int i=0;i<myArray.Length;i++) {
myArray[i] = int.Parse(Console.ReadLine()); //Int32.Parse(Console.ReadLine()) also works
Just like #Furkle said, it is always best to use TryParse() which enables you to perform exception handling. MSDN has a nice tutorial on this.

furkle is correct, it's not working because the console.ReadLine method returns a string, and you can't assign a string to an int array. However, the solution provided is a bit clunky because it only reads one character at a time from the console. It's better to take in all the input at once.
Here is a short console program that
takes in a space separated list of integers from the user
converts the string to a string List using Split(' ').ToList();
Converts the string List to an int List
Reads the contents back to you.
Error handling is included.
static void Main(string[] args){
var intList = new List<int>();
string sUserInput = "";
var sList = new List<string>();
bool validInput = true;
do
{
validInput = true;
Console.WriteLine("input a space separated list of integers");
sUserInput = Console.ReadLine();
sList = sUserInput.Split(' ').ToList();
try
{
foreach (var item in sList) {intList.Add(int.Parse(item));}
}
catch (Exception e)
{
validInput = false;
Console.WriteLine("An error occurred. You may have entered the list incorrectly. Please make sure you only enter integer values separated by a space. \r\n");
}
} while (validInput == false);
Console.WriteLine("\r\nHere are the contents of the intList:");
foreach (var item in intList)
{
Console.WriteLine(item);
}
Console.WriteLine("\r\npress any key to exit...");
Console.ReadKey();
}//end main
If you want to make sure the user only enters a total of 5 integers you can do the DO WHILE loop like this:
do
{
validInput = true;
Console.WriteLine("input a space separated list of integers");
sUserInput = Console.ReadLine();
sList = sUserInput.Split(' ').ToList();
if (sList.Count > 5)
{
validInput = false;
Console.WriteLine("you entered too many integers. You must enter only 5 integers. \r\n");
}
else
{
try
{
foreach (var item in sList) { intList.Add(int.Parse(item)); }
}
catch (Exception e)
{
validInput = false;
Console.WriteLine("An error occurred. You may have entered the list incorrectly. Please make sure you only enter integer values separated by a space. \r\n");
}
}
} while (validInput == false);

Related

Can't add objects to an array after a foreach loop in C#

I can't append an object to an array after a foreach loop. The object is okay, it contains all the right values which I found out through debugging.
In the end I want to have a custom Exercise object which contains a user-chosen number of custom ExerciseAnswer objects also. The array of ExerciseAnswer objects is the problem.
Here is the interesting part of my method:
static void CreateNewExerciseTest()
{
string? exerciseName = "Test Exercise";
string? exerciseTopic = "Test";
string exerciseQuestion = "Does it work?";
int numberOfAnswers = 2;
int numberOfApplicableAnswers = 0;
ExerciseAnswer[] exerciseAnswers = new ExerciseAnswer[2];
foreach (ExerciseAnswer answer in exerciseAnswers)
{
int exerciseAnswerId = GenerateId();
Console.WriteLine("\nEnter a name for this Exercise answer: ");
string? exerciseAnswerName = Console.ReadLine();
Console.WriteLine("Enter this answer for the Exercise: ");
string exerciseAnswerContent = Console.ReadLine();
Console.WriteLine("Enter y (yes) if this Exercise answer is applicable,
otherwise press n (no) or any other key: ");
char applicableAnswer = Console.ReadKey().KeyChar;
bool applicable = ExerciseAnswer.EvaluateExerciseAnswer(applicableAnswer);
if (applicable == true)
{
numberOfApplicableAnswers++;
}
ExerciseAnswer exerciseAnswer = new ExerciseAnswer(exerciseAnswerId,
exerciseAnswerName, exerciseAnswerContent, applicable);
exerciseAnswers.Append(exerciseAnswer);
// ...
}
}
This the GenerateId method:
static int GenerateId()
{
return ++id;
}
The array exerciseAnswers does not contain the ExerciseAnswer elements it should while the exerciseAnswer object in the line above does. Maybe the problem is related to the declaration and initialization of exerciseAnswers and the foreach loop.
Has somebody have an idea?
Thank you!
I believe you are using Append method from System.Linq namespace
public static IEnumerable<TSource> Append<TSource>(this IEnumerable<TSource> source, TSource element);
This method returns a new IEnumerable which contains your exerciceAnswer
With this piece of code you can understand what is going on:
var result = exerciseAnswers.Append(exerciseAnswer);
Console.WriteLine($"exerciseAnswers count = {exerciseAnswers.Count()}");
Console.WriteLine($"result count = {result.Count()}");
Console output:
exerciseAnswers count = 2
result count = 3
Append will just append to existing elements of array, since in your case size is already defined as 2(new ExerciseAnswer[2]) so it is not appending anything. What you can do is either have a new array and get the elements added to it or just get the index of element you are running the loop and replace same in the array.
Something like below:-
int elementIndex = Array.IndexOf(exerciseAnswers,answer);
exerciseAnswers[elementIndex] = exerciseAnswer;

C# read value from user console.read [duplicate]

What I am looking for is how to read an integer that was given by the user from the command line (console project). I primarily know C++ and have started down the C# path. I know that Console.ReadLine(); only takes a char/string. So in short I am looking for the integer version of this.
Just to give you an idea of what I'm doing exactly:
Console.WriteLine("1. Add account.");
Console.WriteLine("Enter choice: ");
Console.ReadLine(); // Needs to take in int rather than string or char.
I have been looking for quite a while for this. I have found a lot on C but not C#. I did find however a thread, on another site, that suggested to convert from char to int. I'm sure there has to be a more direct way than converting.
You can convert the string to integer using Convert.ToInt32() function
int intTemp = Convert.ToInt32(Console.ReadLine());
I would suggest you use TryParse:
Console.WriteLine("1. Add account.");
Console.WriteLine("Enter choice: ");
string input = Console.ReadLine();
int number;
Int32.TryParse(input, out number);
This way, your application does not throw an exception, if you try to parse something like "1q" or "23e", because somebody made a faulty input.
Int32.TryParse returns a boolean value, so you can use it in an if statement, to see whether or not you need to branch of your code:
int number;
if(!Int32.TryParse(input, out number))
{
//no, not able to parse, repeat, throw exception, use fallback value?
}
To your question: You will not find a solution to read an integer because ReadLine() reads the whole command line, threfor returns a string. What you can do is, try to convert this input into and int16/32/64 variable.
There are several methods for this:
Int.Parse()
Convert.ToInt()
Int.TryParse()
If you are in doubt about the input, which is to be converted, always go for the TryParse methods, no matter if you try to parse strings, int variable or what not.
Update
In C# 7.0 out variables can be declared directly where they are passed in as an argument, so the above code could be condensed into this:
if(Int32.TryParse(input, out int number))
{
/* Yes input could be parsed and we can now use number in this code block
scope */
}
else
{
/* No, input could not be parsed to an integer */
}
A complete example would look like this:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
var foo = Console.ReadLine();
if (int.TryParse(foo, out int number1)) {
Console.WriteLine($"{number1} is a number");
}
else
{
Console.WriteLine($"{foo} is not a number");
}
Console.WriteLine($"The value of the variable {nameof(number1)} is {number1}");
Console.ReadLine();
}
}
Here you can see, that the variable number1 does get initialized even if the input is not a number and has the value 0 regardless, so it is valid even outside the declaring if block
You need to typecast the input. try using the following
int input = Convert.ToInt32(Console.ReadLine());
It will throw exception if the value is non-numeric.
Edit
I understand that the above is a quick one. I would like to improve my answer:
String input = Console.ReadLine();
int selectedOption;
if(int.TryParse(input, out selectedOption))
{
switch(selectedOption)
{
case 1:
//your code here.
break;
case 2:
//another one.
break;
//. and so on, default..
}
}
else
{
//print error indicating non-numeric input is unsupported or something more meaningful.
}
int op = 0;
string in = string.Empty;
do
{
Console.WriteLine("enter choice");
in = Console.ReadLine();
} while (!int.TryParse(in, out op));
Use this simple line:
int x = int.Parse(Console.ReadLine());
I didn't see a good and complete answer to your question, so I will show a more complete example. There are some methods posted showing how to get integer input from the user, but whenever you do this you usually also need to
validate the input
display an error message if invalid input
is given, and
loop through until a valid input is given.
This example shows how to get an integer value from the user that is equal to or greater than 1. If invalid input is given, it will catch the error, display an error message, and request the user to try again for a correct input.
static void Main(string[] args)
{
int intUserInput = 0;
bool validUserInput = false;
while (validUserInput == false)
{
try
{
Console.Write("Please enter an integer value greater than or equal to 1: ");
intUserInput = int.Parse(Console.ReadLine()); //try to parse the user input to an int variable
}
catch (Exception e) //catch exception for invalid input, such as a letter
{
Console.WriteLine(e.Message);
}
if (intUserInput >= 1) { validUserInput = true; }
else { Console.WriteLine(intUserInput + " is not a valid input, please enter an integer greater than 0."); }
} //end while
Console.WriteLine("You entered " + intUserInput);
Console.WriteLine("Press any key to exit ");
Console.ReadKey();
} //end main
In your question it looks like you wanted to use this for menu options. So if you wanted to get int input for choosing a menu option you could change the if statement to
if ( (intUserInput >= 1) && (intUserInput <= 4) )
This would work if you needed the user to pick an option of 1, 2, 3, or 4.
I used int intTemp = Convert.ToInt32(Console.ReadLine()); and it worked well, here's my example:
int balance = 10000;
int retrieve = 0;
Console.Write("Hello, write the amount you want to retrieve: ");
retrieve = Convert.ToInt32(Console.ReadLine());
Better way is to use TryParse:
Int32 _userInput;
if(Int32.TryParse (Console.Readline(), out _userInput) {// do the stuff on userInput}
Try this it will not throw exception and user can try again:
Console.WriteLine("1. Add account.");
Console.WriteLine("Enter choice: ");
int choice = 0;
while (!Int32.TryParse(Console.ReadLine(), out choice))
{
Console.WriteLine("Wrong input! Enter choice number again:");
}
static void Main(string[] args)
{
Console.WriteLine("Please enter a number from 1 to 10");
int counter = Convert.ToInt32(Console.ReadLine());
//Here is your variable
Console.WriteLine("The numbers start from");
do
{
counter++;
Console.Write(counter + ", ");
} while (counter < 100);
Console.ReadKey();
}
You could create your own ReadInt function, that only allows numbers
(this function is probably not the best way to go about this, but does the job)
public static int ReadInt()
{
string allowedChars = "0123456789";
ConsoleKeyInfo read = new ConsoleKeyInfo();
List<char> outInt = new List<char>();
while(!(read.Key == ConsoleKey.Enter && outInt.Count > 0))
{
read = Console.ReadKey(true);
if (allowedChars.Contains(read.KeyChar.ToString()))
{
outInt.Add(read.KeyChar);
Console.Write(read.KeyChar.ToString());
}
if(read.Key == ConsoleKey.Backspace)
{
if(outInt.Count > 0)
{
outInt.RemoveAt(outInt.Count - 1);
Console.CursorLeft--;
Console.Write(" ");
Console.CursorLeft--;
}
}
}
Console.SetCursorPosition(0, Console.CursorTop + 1);
return int.Parse(new string(outInt.ToArray()));
}
Declare a variable that will contain the value of the user input :
Ex :
int userInput = Convert.ToInt32(Console.ReadLine());
I know this question is old, but with some newer C# features like lambda expressions, here's what I actually implemented for my project today:
private static async Task Main()
{
// -- More of my code here
Console.WriteLine("1. Add account.");
Console.WriteLine("2. View accounts.");
int choice = ReadInt("Please enter your choice: ");
// -- Code that uses the choice variable
}
// I have this as a public function in a utility class,
// but you could use it directly in Program.cs
private static int ReadInt(string prompt)
{
string? text;
do
{
Console.Write(prompt);
text = Console.ReadLine();
} while (text == null || !text.Where(c => char.IsNumber(c)).Any());
return int.Parse(new string(text.Where(c => char.IsNumber(c)).ToArray()));
}
The difference here is that if you accidentally type a number and any other text along with that number, only the number is parsed.
You could just go ahead and try :
Console.WriteLine("1. Add account.");
Console.WriteLine("Enter choice: ");
int choice=int.Parse(Console.ReadLine());
That should work for the case statement.
It works with the switch statement and doesn't throw an exception.

How to output "EVEN" for even numbers between 1 and 100?

How to write C# code that lists out object array value int 1-100 and output string text "EVEN" when it detect that object converted to int is divisible by 2?
class Program
{
static void Main(string[] args)
{
object[] numbers = new object[100];
numbers = Enumerable.Range(1, 100).Cast<object>().ToArray();
foreach (object number in numbers)
{
if(Convert.ToInt32(number) % 2 == 0)
{
number.ToString().Equals("Even");
}
Console.WriteLine(number);
}
Console.Read();
}
}
The problem you have is here:
number.ToString().Equals("Even");
This is getting the string representation of number and then comparing it for equality against the string Even, and doing nothing with the result. If you take a step back and think about this, it doesn't make any sense, because you want to print Even if number is even.
With your current program, you can do that like this:
if (Convert.ToInt32(number) % 2 == 0)
{
Console.WriteLine("{0} is even", number);
}
That said, there are a few things with your program that could be improved, as it doesn't seem as though you've got the hang of C#'s type system just yet.
Firstly, you are declaring an array of 100 objects like so:
object[] numbers = new object[100];
You already know you want to work with integers, so, instead of using object, you should use int:
int[] numbers = new int[100];
Next, you're generating a sequence of integers from 1-100:
numbers = Enumerable.Range(1, 100).Cast<object>().ToArray();
Enumerable.Range() returns a collection of integers, and .ToArray() converts that to an array of integers. As we're now using an array of integers, there is no need to cast them to object, so this can be simplified to:
numbers = Enumerable.Range(1, 100).ToArray();
There is one further simplification that can be made to this. Enumerable.Range() returns an IEnumerable<int>, which represents a collection of integers. This means that instead of declaring an array of 100 integers, generating a collection of integers, converting those to an array, and assigning them to numbers, we can do this instead:
IEnumerable<int> numbers = Enumerable.Range(1, 100);
There is another change that can be made here, but I'll describe at the end of this answer so let's look at the loop:
foreach (object number in numbers)
{
if (Convert.ToInt32(number) % 2 == 0)
{
Console.WriteLine(number);
}
}
As we've changed the code to use IEnumerable<int> instead of object[], we can now change the declaration of the loop to:
foreach (int number in numbers)
This is possible because a type that implements IEnumerable allows you to use foreach. As another example, if we had a collection of students:
IEnumerable<Student> students = GetStudents();
We could loop over those like this:
foreach (Student student in students)
Going back to your loop, now that number is an int, we don't have to convert it from an object to an int before we can check if it's even or not. So the loop's code can be simplified to:
foreach (int number in numbers)
{
if (number % 2 == 0)
{
Console.WriteLine("{0} is even", number);
}
}
The main thing to understand is that when you already know what type you'd like to use, you should always use it whenever you can, as it will always simplify the code you write. The complete program would now look like this:
class Program
{
static void Main(string[] args)
{
IEnumerable<int> numbers = Enumerable.Range(1, 100);
foreach (int number in numbers)
{
if (number % 2 == 0)
{
Console.WriteLine("{0} is even", number);
}
}
Console.Read();
}
}
As for the other change I mentioned, your integer generation code could be simplified to:
var numbers = Enumerable.Range(1, 100);
The var keyword is making use of implicit type inference to determine numbers type. Similarly, the loop could also be changed to:
foreach (var number in numbers)
I wouldn't worry about implicit type inference for the moment. I'm mentioning more for the sake of completeness, but you should learn to use the type system properly first.
Your code is almost correct (except for the .Equals("Even") part). Your code inside the foreachcan be simplified to:
Console.WriteLine(number.ToString() + ((Convert.ToInt32(number) % 2) == 0 ? " is even" : ""));
}
Check this code snippets.
class Program
{
static void Main(string[] args)
{
var stringBuilder = new StringBuilder();
var numbers = new List<object>();
numbers = Enumerable.Range(0, 100).Cast<object> ().ToList();
foreach (var number in numbers)
{
if (Convert.ToInt32(number) % 2 == 0)
stringBuilder.Append("EVEN");
else
stringBuilder.Append(number);
}
Console.WriteLine(stringBuilder.ToString());
}
}
Please let me know if this snippets could solve your problems

Reading an integer from user input

What I am looking for is how to read an integer that was given by the user from the command line (console project). I primarily know C++ and have started down the C# path. I know that Console.ReadLine(); only takes a char/string. So in short I am looking for the integer version of this.
Just to give you an idea of what I'm doing exactly:
Console.WriteLine("1. Add account.");
Console.WriteLine("Enter choice: ");
Console.ReadLine(); // Needs to take in int rather than string or char.
I have been looking for quite a while for this. I have found a lot on C but not C#. I did find however a thread, on another site, that suggested to convert from char to int. I'm sure there has to be a more direct way than converting.
You can convert the string to integer using Convert.ToInt32() function
int intTemp = Convert.ToInt32(Console.ReadLine());
I would suggest you use TryParse:
Console.WriteLine("1. Add account.");
Console.WriteLine("Enter choice: ");
string input = Console.ReadLine();
int number;
Int32.TryParse(input, out number);
This way, your application does not throw an exception, if you try to parse something like "1q" or "23e", because somebody made a faulty input.
Int32.TryParse returns a boolean value, so you can use it in an if statement, to see whether or not you need to branch of your code:
int number;
if(!Int32.TryParse(input, out number))
{
//no, not able to parse, repeat, throw exception, use fallback value?
}
To your question: You will not find a solution to read an integer because ReadLine() reads the whole command line, threfor returns a string. What you can do is, try to convert this input into and int16/32/64 variable.
There are several methods for this:
Int.Parse()
Convert.ToInt()
Int.TryParse()
If you are in doubt about the input, which is to be converted, always go for the TryParse methods, no matter if you try to parse strings, int variable or what not.
Update
In C# 7.0 out variables can be declared directly where they are passed in as an argument, so the above code could be condensed into this:
if(Int32.TryParse(input, out int number))
{
/* Yes input could be parsed and we can now use number in this code block
scope */
}
else
{
/* No, input could not be parsed to an integer */
}
A complete example would look like this:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
var foo = Console.ReadLine();
if (int.TryParse(foo, out int number1)) {
Console.WriteLine($"{number1} is a number");
}
else
{
Console.WriteLine($"{foo} is not a number");
}
Console.WriteLine($"The value of the variable {nameof(number1)} is {number1}");
Console.ReadLine();
}
}
Here you can see, that the variable number1 does get initialized even if the input is not a number and has the value 0 regardless, so it is valid even outside the declaring if block
You need to typecast the input. try using the following
int input = Convert.ToInt32(Console.ReadLine());
It will throw exception if the value is non-numeric.
Edit
I understand that the above is a quick one. I would like to improve my answer:
String input = Console.ReadLine();
int selectedOption;
if(int.TryParse(input, out selectedOption))
{
switch(selectedOption)
{
case 1:
//your code here.
break;
case 2:
//another one.
break;
//. and so on, default..
}
}
else
{
//print error indicating non-numeric input is unsupported or something more meaningful.
}
int op = 0;
string in = string.Empty;
do
{
Console.WriteLine("enter choice");
in = Console.ReadLine();
} while (!int.TryParse(in, out op));
Use this simple line:
int x = int.Parse(Console.ReadLine());
I didn't see a good and complete answer to your question, so I will show a more complete example. There are some methods posted showing how to get integer input from the user, but whenever you do this you usually also need to
validate the input
display an error message if invalid input
is given, and
loop through until a valid input is given.
This example shows how to get an integer value from the user that is equal to or greater than 1. If invalid input is given, it will catch the error, display an error message, and request the user to try again for a correct input.
static void Main(string[] args)
{
int intUserInput = 0;
bool validUserInput = false;
while (validUserInput == false)
{
try
{
Console.Write("Please enter an integer value greater than or equal to 1: ");
intUserInput = int.Parse(Console.ReadLine()); //try to parse the user input to an int variable
}
catch (Exception e) //catch exception for invalid input, such as a letter
{
Console.WriteLine(e.Message);
}
if (intUserInput >= 1) { validUserInput = true; }
else { Console.WriteLine(intUserInput + " is not a valid input, please enter an integer greater than 0."); }
} //end while
Console.WriteLine("You entered " + intUserInput);
Console.WriteLine("Press any key to exit ");
Console.ReadKey();
} //end main
In your question it looks like you wanted to use this for menu options. So if you wanted to get int input for choosing a menu option you could change the if statement to
if ( (intUserInput >= 1) && (intUserInput <= 4) )
This would work if you needed the user to pick an option of 1, 2, 3, or 4.
I used int intTemp = Convert.ToInt32(Console.ReadLine()); and it worked well, here's my example:
int balance = 10000;
int retrieve = 0;
Console.Write("Hello, write the amount you want to retrieve: ");
retrieve = Convert.ToInt32(Console.ReadLine());
Better way is to use TryParse:
Int32 _userInput;
if(Int32.TryParse (Console.Readline(), out _userInput) {// do the stuff on userInput}
Try this it will not throw exception and user can try again:
Console.WriteLine("1. Add account.");
Console.WriteLine("Enter choice: ");
int choice = 0;
while (!Int32.TryParse(Console.ReadLine(), out choice))
{
Console.WriteLine("Wrong input! Enter choice number again:");
}
static void Main(string[] args)
{
Console.WriteLine("Please enter a number from 1 to 10");
int counter = Convert.ToInt32(Console.ReadLine());
//Here is your variable
Console.WriteLine("The numbers start from");
do
{
counter++;
Console.Write(counter + ", ");
} while (counter < 100);
Console.ReadKey();
}
You could create your own ReadInt function, that only allows numbers
(this function is probably not the best way to go about this, but does the job)
public static int ReadInt()
{
string allowedChars = "0123456789";
ConsoleKeyInfo read = new ConsoleKeyInfo();
List<char> outInt = new List<char>();
while(!(read.Key == ConsoleKey.Enter && outInt.Count > 0))
{
read = Console.ReadKey(true);
if (allowedChars.Contains(read.KeyChar.ToString()))
{
outInt.Add(read.KeyChar);
Console.Write(read.KeyChar.ToString());
}
if(read.Key == ConsoleKey.Backspace)
{
if(outInt.Count > 0)
{
outInt.RemoveAt(outInt.Count - 1);
Console.CursorLeft--;
Console.Write(" ");
Console.CursorLeft--;
}
}
}
Console.SetCursorPosition(0, Console.CursorTop + 1);
return int.Parse(new string(outInt.ToArray()));
}
Declare a variable that will contain the value of the user input :
Ex :
int userInput = Convert.ToInt32(Console.ReadLine());
I know this question is old, but with some newer C# features like lambda expressions, here's what I actually implemented for my project today:
private static async Task Main()
{
// -- More of my code here
Console.WriteLine("1. Add account.");
Console.WriteLine("2. View accounts.");
int choice = ReadInt("Please enter your choice: ");
// -- Code that uses the choice variable
}
// I have this as a public function in a utility class,
// but you could use it directly in Program.cs
private static int ReadInt(string prompt)
{
string? text;
do
{
Console.Write(prompt);
text = Console.ReadLine();
} while (text == null || !text.Where(c => char.IsNumber(c)).Any());
return int.Parse(new string(text.Where(c => char.IsNumber(c)).ToArray()));
}
The difference here is that if you accidentally type a number and any other text along with that number, only the number is parsed.
You could just go ahead and try :
Console.WriteLine("1. Add account.");
Console.WriteLine("Enter choice: ");
int choice=int.Parse(Console.ReadLine());
That should work for the case statement.
It works with the switch statement and doesn't throw an exception.

How to fill an array with user input without specifying length of array yourself in code

So I'm trying to fill a char array with user input. However I do not want to specify the length of the array myself, thus limiting the user to the amount they can input. For example my code below will only allow the user to enter 5 characters and then will exit. Code in any language would be fine. (The below is C#).
Console.Write("Enter a number of characters of your choice...click 1 to exit: ");
bool exitCondition;
int counter = 0;
char[] character = new char[5];
do
{
exitCondition = false;
try
{
character[counter] = char.Parse(Console.ReadLine());
if (character[counter] == '1')
exitCondition = true;
}
catch (Exception ex)
{
Console.WriteLine("Error: {0}", ex.Message);
}
counter++;
}
while (exitCondition == false && counter < 5);
You need to use a collection, which allows the collection of elements to grow or shrink. In Java an ArrayList would be appropriate for your scenario. In C# you would most likely use a List.
C#
List<char> list = new List<char>();
list.Add('a');
list.Add('b');
Java
List<Character> list = new ArrayList<Character>();
list.add('a');
Array's are static in size. Use java.util.ArrayList ( from Collection framework) which is resizable-array.
List<Character> chars = new ArrayList<Character>();
chars.add('a');
chars.add('c');
chars.add('d');
Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null. In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list.
Ref
StringBuilder is all you need
StringBuidler sb = new StringBuilder();
sb.append(c);
...
then you can get char array from it if you really want it
char[] a = sb.toString().toCharArray();
though typically it is just converted into a String
String s = sb.toString()
there is also a method to work with StringBuilder internal char[] directly
char c = sb.charAt(i)
Alternatively if you really want to use only array for some hidden reason :), then you can ask user for number of input items and initialize array accordingly.
Thanks,
Naval

Categories