|
-
November 30th, 2011, 07:28 AM
#1
How to enter several numbers to array in one line?
I'm using Visual Studio 2010 and new to C#
I want to ask 5 different numbers from user to an int-array. Is it possible for user to enter all numbers in one line separated with space or comma?
Like "Enter 5 numbers:3,5,11,15,46" or "3 5 11 15 46"
I can code this by user entering each number in its own line and pressing enter between numbers but I was curious and thought could I do this in one line. 
Thanks for help!
-
November 30th, 2011, 09:11 AM
#2
Re: How to enter several numbers to array in one line?
It's pretty simple. You declare the values you want within curly braces after the initialization.
Code:
int[] intArray = new int[5] {3,5,11,15,46};
HTH
Code:
if (Issue.Resolved)
{
ThreadTools.Click();
MarkThreadResolved();
}
-
November 30th, 2011, 10:49 AM
#3
Re: How to enter several numbers to array in one line?
Take a look at the split function it allows you to get an array from a single line.
For example
Code:
This is a split
Becomes:
This
is
a
split
It allows you to choose what character divides your string and removes that character from the output.
For example (',', '/', '.', '\t', ' ')
Code:
string line = "This is a simple example, but it may help you understand.";
string[] words = line.Split(new char[] { ' ', ',', '.'});
foreach (string word in words)
{
Console.WriteLine(word);
}
Console.ReadKey();
Test the code above and remove each of the delimiters one at a time and see the effects. So for example on test two and three the line can read
Code:
// Test Two:
line.Split(new char[] { ' ', ',' });
// Test Three
line.Split(new char[] { ',', '.'});
-
November 30th, 2011, 11:20 AM
#4
Re: How to enter several numbers to array in one line?
Thanks Ubiquitous!
That was the solution I wanted.
-
November 30th, 2011, 12:34 PM
#5
Re: How to enter several numbers to array in one line?
You may also skip '5' in new int[5]
Code:
int[] myArray = new int[] {0,1,2,3,4,5,6}; // This array will have size of 7 (0-6)
With lists is similar, you just need to add () before {}
Code:
List<Type> myList = new List<Type>(){};
-
December 1st, 2011, 07:36 AM
#6
Re: How to enter several numbers to array in one line?
Now I ran to one small problem.
I ask user to input numbers into string line. And then I parse string array to another int-array.
How I make a check if there were incorrect values (like chars or letters)? Only numbers are accepted and from a specific gap, like 1-20.
If the user enters wrong values, the program loops back to asking new numbers.
Been trying to mess with try-catch and do-while loops but no profit.
E: I managed something with try-catch. When user inputs something which is not a number, the program catches Formatexception. But it keeps asking it because I dont know how to end that loop when input is correct.
Last edited by erkki4; December 1st, 2011 at 07:42 AM.
-
December 1st, 2011, 01:32 PM
#7
Re: How to enter several numbers to array in one line?
I am not sure what you are trying to accomplish perhaps you could enter a portion of your code so we can help you better.
To end a loop early use a break:
Example
Code:
Foreach (string word in line)
{
if (word == "test")
{
break;
}
}
As soon as a word matches the chosen word it will break out of the loop.
Sorry I can't use more elaborate examples I am at work right now. Post what you are trying to do in a little more detail so we can try to help you better.
By the way if you want it to keep looping until the user's input is correct then you will need a while loop.
-
December 1st, 2011, 10:25 PM
#8
Re: How to enter several numbers to array in one line?
Here is some simple example code that loops requesting input until the user gives valid input.
Code:
bool valid = false;
int[] result;
while( !valid )
{
Console.Write("Give me some numbers!: ");
string input = Console.ReadLine(); //Read user input
string[] inputSplit = input.Split(' '); //Split by spaces
result = new int[inputSplit.Length];
//Assume input is valid until proven otherwise
valid = true;
for(int i = 0; i < inputSplit.Length; i++)
{
//Try to parse the subset of the input string and store the result in
// result[i]. TryParse returns a bool telling whether the parsing was
// successful or not.
bool parseSuccessful = Int32.TryParse(inputSplit[i], out result[i]);
//If the parsing wasn't successful
if( !parseSuccessful )
{
//Then we got invalid input
valid = false;
break; //Abort parsing immediately and request new input
}
//Add any other checks you want here. For example, to disallow any entry to be zero:
if( result[i] == 0 )
{
valid = false;
break;
}
//Display an error message before re-running this loop if invalid input
if( !valid )
Console.WriteLine("Hey! You didn't give me valid data!");
}
This is much better than trying to use try-catch. Your program should only throw exceptions in exceptional circumstances. The user entering invalid data is expected, not exceptional. Use of TryParse returning a bool indicating the success of parsing (instead of using Parse and then catching the FormatException) is better design.
Make sense?
Best Regards,
BioPhysEngr
http://blog.biophysengr.net
--
All advice is offered in good faith only. You are ultimately responsible for effects of your programs and the integrity of the machines they run on.
-
December 2nd, 2011, 02:07 PM
#9
Re: How to enter several numbers to array in one line?
to BioPhysEngr:
Yeah that makes some sense. I have to try that when got time.
I managed something with try-catch too. I have do-while loop and bool variable and put it in the while(). And if exception happens. It changes the value so it jumps out of loop.
But if try-catch is bad choice then I have to try that method.
-
December 2nd, 2011, 03:23 PM
#10
Re: How to enter several numbers to array in one line?
don't use the side effect of exception to deal with invalid data because exception is expensive
-
December 9th, 2011, 04:36 PM
#11
Re: How to enter several numbers to array in one line?
Ok thank you BioPhysEngr for that solution. It made my program much more clear. 
But if I want to limit entered numbers to for example 10, can I use try-catch then? Because when I want ten numbers and have int array size of 10 and the user inputs 11 numbers, It gets this unhandled exception.
Or is there another way round this?
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|