The goal of the code is to take a string of numbers separated by hyphens and check if they are consecutive.
I have tried using string.spit, iterating over the array and checking if the number +1 is equal to the next value. But I've run into an issue of the index I'm working on exceeding the bounds of the array.
Here is the current build.
public static void Consecutive()
{
Console.Write("enter multiple numbers separated by hyphens: ");
var userinput = Console.ReadLine();
var nums = userinput.Split();
int index = 0;
bool isConsecutive = false;
foreach(var number in nums)
{
if(Convert.ToInt32(nums[index + 1]) == Convert.ToInt32(nums[index] + 1))
{
isConsecutive = true;
}
else
{
isConsecutive = false;
}
if(index == nums.Length)
{
break;
}
}
Console.WriteLine(isConsecutive);
}
You want to split by hyphens, but you split by white-spaces. You also don't use the number loop variable of the foreach. For what you are doing a for-loop is much more appropriate anyway:
public static void Consecutive()
{
Console.WriteLine("enter multiple numbers separated by hyphens: ");
string userinput = Console.ReadLine();
string[] nums = userinput.Split('-');
// always validate input
while (!nums.All(n => n.All(char.IsDigit)))
{
Console.WriteLine("All numbers must be valid integers");
userinput = Console.ReadLine();
nums = userinput.Split('-');
}
bool isConsecutive = true;
for(int i = 1; i < nums.Length; i++)
{
int thisInt = int.Parse(nums[i]);
int prevInt = int.Parse(nums[i - 1]);
if(thisInt != prevInt + 1)
{
isConsecutive = false;
break;
}
}
Console.WriteLine(isConsecutive);
}
This is because when the foreach loop iterates over the last element there is no element with index + 1 and your check if(index == nums.Length) does not work.
Explanation:
nums.Length = last index + 1.
For an array with 5 elements, the length = 5 and the last index = 4.
Because of that your if condition is never true.
Solution:
Change the condition from if(index == nums.Length) to if(index == nums.Length - 1)
Here's a different approach, generating the expected sequence and seeing if that matches the cleansed input:
var delimiter = ",";
Console.Write("Enter multiple integers separated by '" + delimiter + "': ");
var userinput = Console.ReadLine(); ;
bool isConsecutive = false;
try
{
var strNums = userinput.Split(delimiter.ToCharArray());
var nums = Array.ConvertAll(strNums, x => int.Parse(x));
var consecutive = Enumerable.Range(nums[0], nums.Length);
var strCleansed = String.Join(delimiter, nums);
var strGenerated = String.Join(delimiter, consecutive);
isConsecutive = (strCleansed == strGenerated);
Console.WriteLine(" cleansed = " + strCleansed);
Console.WriteLine(" generated = " + strGenerated);
}
catch (Exception)
{
Console.WriteLine("Invalid Integer in Input");
}
Console.WriteLine("isConsecutive = " + isConsecutive);
Console.ReadKey();
Sample runs:
Enter multiple integers separated by ',': -3, -0000002, -1, 0, 1, 02, 3
cleansed = -3,-2,-1,0,1,2,3
generated = -3,-2,-1,0,1,2,3
isConsecutive = True
Enter multiple integers separated by ',': 1,2,3,5
cleansed = 1,2,3,5
generated = 1,2,3,4
isConsecutive = False
Enter multiple integers separated by ',': 1,fish,2,fish,red fish,blue fish
Invalid Integer in Input
isConsecutive = False
Related
I am writing code that will count the number of times each word in an array appears as well as the total of number of all the words appearing. I have managed to create an array which allows the user to add in a number of words they wish to check. However, I am struggling to find a way to count the number of times each word is within the sentence individually (I can only get it working for the first element of the array).
I have tried a for loop that when completed it will move to the next element in the array but it does not start for loop again for the next element but ends the code block.
int occurences = 0;
string[] words = new string[_wordCount];
for (int i = 0; i < words.Length; i++)
{
Console.WriteLine("Type in the censored words you wish to be counted: ");
words[i] = Console.ReadLine();
if (_sentence.Contains(words[i]))
{
occurences++;
}
if (i > words.Length)
{
i++;
}
}
Console.WriteLine("Number of censored word occurences: " + occurences);
return occurences;
You simply need to calculate each word occurrence separately like this:
int i, j, woccurence, occurences = 0;
string[] words, details = new string[_wordCount];
for (i = 0; i < words.Length; i++)
{
Console.WriteLine("Type in the censored words you wish to be counted: ");
words[i] = Console.ReadLine();
woccurence = 0;
details = _sentence.Split(' ');
for (j = 0; j < details.Length; j++)
if (details[j] == words[i])
woccurences++;
Console.WriteLine("Number of censored word occurences: " + woccurences);
occurences += woccurences;
}
Console.WriteLine("Number of total censored words occurences: " + occurences);
return occurences;
Details
In each cycle of the loop, you count the number of occurrences of a word from the beginning using woccurence and print it out, then you add this value to the total occurrence.
if sentence consists of words seperated by a space, you can use string.split to make it an array that you can then iterate throguh.
var sentenceArray = _sentence.Split(new Char [] {' '});
And then loop through sentence array within your main words loop.
I don't see where _sentence or _wordCount are being set, but let me know if this is what you have in mind.
Caveat: I'm assuming here the user will input each word with a single space between words when prompted. You'll probably want to handle the case where user uses too much space, commas, etc.
static int GetWords()
{
int occurences = 0;
int _wordCount = 0;
string _sentence = "The quick brown fox jumped over the lazy dog.";
string[] words = new string[_sentence.Length];
Console.WriteLine("Type in the censored words you wish to be counted: ");
string censoredWordString = Console.ReadLine();
string[] censoredWords = censoredWordString.Split(' ');
for (int i = 0; i < censoredWords.Length; i++)
{
if (_sentence.Contains(censoredWords[i]))
{
occurences++;
}
}
Console.WriteLine("Number of censored word occurences: " + occurences);
return occurences;
}
You can try this:
int occurences = 0;
string sentence = "This is a test sentence. This sentence is test. This sentence do nothing.";
var sentenceWords = new string(sentence.Where(c => !char.IsPunctuation(c)).ToArray()).Split(' ');
var wordsFound = new Dictionary<string, int>();
Console.WriteLine("Sentence = " + sentence);
while ( true)
{
Console.WriteLine(Environment.NewLine);
Console.WriteLine("Type in a censored word you wish to be counted (enter empty to end): ");
string input = Console.ReadLine();
if ( input == "" ) break;
int count = sentenceWords.Count(word => word.ToLower() == input.ToLower());
if ( count == 0 )
{
Console.WriteLine("Can't find \"" + input + "\".");
}
else
{
Console.WriteLine("Found " + count + " occurences of \"" + input + "\".");
if ( !wordsFound.ContainsKey(input) )
wordsFound.Add(input, count);
occurences += count;
}
}
Console.WriteLine(Environment.NewLine);
Console.WriteLine("Number of total censored words occurences: " + occurences);
foreach ( var item in wordsFound)
Console.WriteLine(" " + item.Key + ": " + item.Value);
Console.ReadKey();
You can achieve that only using LINQ
int totalWords = 0;
var sentence = "Don't cry because it's over, smile because it happened";
sentence.ToLower().Split(' ').GroupBy(x => x).ToList().ForEach(x=> {
totalWords += x.Count();
Console.WriteLine($"{x.Key}: {x.Count()}");
});
Console.WriteLine($"Total words: {totalWords}");
First of all we use ToLower() se we can get rid of lower and uppers
Then We split by a space with .Split(' ')
Now we group by each word with GroupBy(x=>x)
We need to use ToList() to cast de IGrouping<T> so we can iterate the results with ForEach
Finally we print the results getting the Key which reffers to the grouped object and use Count() to get the quantity of group contains
Personally, I'd use a dictionary. Specifically with using a <key, value> of string and int.
int occurances = 0;
string[] words = new string[_wordCount];
var results = new Dictionary<string, int>();
var splitSentence = _sentence.Split(' ').ToArray();
for(int i = 0; i < words.Length; i++)
{
Console.WriteLine("Type in the censored words you wish to be counted: ");
words[i] = Console.ReadLine();
if(_sentence.Contains(words[i]))
{
if(!results.ContainsKey(words[i]))
{
results.Add(words[i], 0);
}
for(var j = 0; j < splitSentence.Length; j++)
{
if(splitSentence[j] == words[i])
{
results[words[i]]++;
occurances++;
}
}
}
}
For a dictionary, the first 'parameter' must be unique, so any time a word reappears you just need to check if that key exists first, it'll just add to the count (the value in the key, value pair).
Using LINQ and Regular Expressions:
var sentence = "now is the time for all good men to come, to the aid of their country.";
var words = new[] { "time", "to" };
var wordsHS = words.ToHashSet();
var wordRE = new Regex(#"\w+", RegexOptions.Compiled);
var wordCounts = wordRE.Matches(sentence).Cast<Match>().Select(m => m.Value)
.Where(w => wordsHS.Contains(w))
.GroupBy(w => w)
.Select(wg => new { Word = wg.Key, Count = wg.Count() })
.ToList();
var total = wordCounts.Sum(wc => wc.Count);
I am learning C# and having an issue understanding why my highNumber value is being displayed as 56 when running my code snippet.
//Write a program and ask the user to enter a series of numbers separated by comma. Find the maximum of the numbers
//and display it on the console. For example, if the user enters “5, 3, 8, 1, 4", the program should display 8
int highNumber = 0;
Console.Write("Enter a series of numbers separated by comma: ");
var userInput = Console.ReadLine();
for (var i = 0; i < userInput.Length; i++)
{
if (char.IsNumber(userInput[i]) == true)
{
if (userInput[i] > highNumber)
{
highNumber = Convert.ToInt32(userInput[i]);
}
}
}
Console.WriteLine("The largest number is {0}", Convert.ToInt32(highNumber));
You've entered the ASCII character '8', which has the numeric value 56.
If it's a single digit character then convert it with this
int val = (int)Char.GetNumericValue(userInput[i]);
If it's a numeric string then convert it in one call with this
int val;
bool success = Int32.TryParse(userInput, out val);
or
int val = System.Convert.ToInt32(userInput);
The LordWilmore`s answer is somehow correct if you dont use numbers greater than 10 but you can simplify and make it more accurate as below:
int highNumber = 0;
int valueTemp;
Console.Write("Enter a series of numbers separated by comma: ");
var userInput = Console.ReadLine();
string[] array = userInput.Split(',');
for (var i = 0; i < array.Length; i++)
{
if (int.TryParse(array[i], out valueTemp))
{
if (valueTemp > highNumber)
{
highNumber = valueTemp;
}
}
}
Console.WriteLine("The largest number is {0}", highNumber);
or using Max() function if you have knowledge about the List<> in c#:
int valueTemp;
Console.Write("Enter a series of numbers separated by comma: ");
var userInput = Console.ReadLine();
string[] array = userInput.Split(',');
List<int> intList = new List<int>();
for (var i = 0; i < array.Length; i++)
{
if (int.TryParse(array[i], out valueTemp))
{
intList.Add(valueTemp);
}
}
Console.WriteLine("The largest number is {0}", intList.Max());
This is a more accurate example because if put 3,33,4 in your example it will fail since you get each character and not values separated by comma. In my case I split them into pieces accordingly and then continue to test them appropriately.
Console.ReadLine(); returns a string. When you use the indexer ([i]) on the string you get individual characters, not strings or numbers. What you want is to Split the string by the commas, then use TryParse to ensure that each string is a number:
string userInput = Console.ReadLine();
string[] parts = userInput.Split(',');
for (var i = 0; i < parts.Length; i++)
{
int number;
if (int.TryParse(parts[i], out number))
{
if (number > highNumber)
{
highNumber = number;
}
}
}
My program has to add the previous number entered to the next one. This is what I have so far, and I got stuck. It adds up the number that I have entered, but I don't understand how I have to validate one number from previous.
static void Main(string[] args)
{
const int QUIT = -1;
string inputStr;
int inputInt = 0;
do
{
Console.Write("Type a number (type -1 to quit): ");
inputStr = Console.ReadLine();
bool inputBool = int.TryParse(inputStr, out inputInt);
if (inputBool == true)
inputInt += inputInt;
Console.WriteLine("Sum of the past three numbers is: {0}", inputInt);
} while (inputInt != QUIT);
}
Since there may be an indefinite number of entries, I don't know how to properly use an array.
If you are trying to find sum of numbers take another variable.
static void Main(string[] args)
{
const int QUIT = -1;
string inputStr;
int inputInt = 0,tempint=0;
do
{
Console.Write("Type a number (type -1 to quit): ");
inputStr = Console.ReadLine();
bool inputBool = int.TryParse(inputStr, out tempint);
if (inputBool == true)
{
inputInt += tempint;
}
Console.WriteLine("Sum of the past three numbers is: {0}", inputInt);
} while (tempint!= QUIT);
}
If you want the simplest solution, you can just keep track of the past 3 numbers and sum them up when you print
static void Main(string[] args)
{
const int QUIT = -1;
string inputStr;
int i1 = 0;
int i2 = 0;
int i3 = 0;
int inputInt = 0;
do
{
Console.Write("Type a number (type -1 to quit): ");
inputStr = Console.ReadLine();
bool inputBool = int.TryParse(inputStr, out inputInt);
if (inputBool == true)
{
i3 = i2;
i2 = i1;
i1 = inputInt;
}
Console.WriteLine("Sum of the past three numbers is: {0}", i1+i2+i3);
} while (inputInt != QUIT);
}
This answer uses LINQ and Queues to do what you want.
static void Main(string[] args)
{
const int QUIT = -1;
string inputStr;
int inputInt = 0;
Queue myQ = new Queue();
do
{
Console.Write("Type a number (type -1 to quit): ");
inputStr = Console.ReadLine();
bool inputBool = int.TryParse(inputStr, out inputInt);
if (inputBool == true)
{
if (myQ.Count() == 3)
{
myQ.Dequeue();
myQ.Enqueue(inputInt);
}
else
{
myQ.Enqueue(inputInt);
}
}
if (myQ.Count() == 3)
{
Console.WriteLine("Sum of the past three numbers is: {0}", myQ.Sum());
}
} while (inputInt != QUIT);
}
Use a list to store all of the numbers as they come in. Then at the end count how many items are in the list, and Sum() the entire list
static void Main(string[] args)
{
const int QUIT = -1;
string inputStr;
List<int> allNumbers = new List<int>();
do
{
Console.Write("Type a number (type -1 to quit): ");
inputStr = Console.ReadLine();
bool inputBool = int.TryParse(inputStr, out inputInt);
if (inputBool == true)
allNumbers.Add(inputInt); // Add a new element to the list
Console.WriteLine("Sum of the past " + allNumbers.Count + " numbers is: {0}", allNumbers.Sum());
} while (inputInt != QUIT);
}
you need to create a local variable to hold the output from int.TryParse. Also you do not need a do while loop, you can exit immediately when the input is -1. With these changes, keeping up with the last 3 numbers becomes much easier:
static void Main(string[] args)
{
const int QUIT = -1;
int[] last3 = new int[3];
// infinite loop, exit is done when input is -1
for(;;) {
Console.Write("Type a number (type -1 to quit): ");
var input = Console.ReadLine();
int tmp; // holds the int value of the input
if (int.TryParse(input, out tmp))
{
if (tmp == QUIT)
break; // input is -1
// input was an int, so lets move the last two towards
// the front of the array, last3[0] contained the oldest value
// which is gone now
last3[0] = last3[1];
last3[1] = last3[2];
// now overwrite the last item in the array with the newest value
last3[2] = tmp;
}
// add up the values, note if input was not a valid int, this will sum
// the last 3 valid values because the above if statement will only execute
// and change the values in the array if the user input was a number
var sum = last3[0] + last3[1] + last3[2];
Console.WriteLine("Sum of the past three numbers is: {0}", sum);
}
}
Not entirely sure this is possible, but say I have two strings like so:
"IAmAString-00001"
"IAmAString-00023"
What would be a quick'n'easy way to iterate from IAmAString-0001 to IAmAString-00023 by moving up the index of just the numbers on the end?
The problem is a bit more general than that, for example the string I could be dealing could be of any format but the last bunch of chars will always be numbers, so something like Super_Confusing-String#w00t0003 and in that case the last 0003 would be what I'd use to iterate through.
Any ideas?
You can use char.IsDigit:
static void Main(string[] args)
{
var s = "IAmAString-00001";
int index = -1;
for (int i = 0; i < s.Length; i++)
{
if (char.IsDigit(s[i]))
{
index = i;
break;
}
}
if (index == -1)
Console.WriteLine("digits not found");
else
Console.WriteLine("digits: {0}", s.Substring(index));
}
which produces this output:
digits: 00001
string.Format and a for loop should do what you want.
for(int i = 0; i <=23; i++)
{
string.Format("IAmAString-{0:D4}",i);
}
or something close to that (not sitting in front of a compiler).
string start = "IAmAString-00001";
string end = "IAmAString-00023";
// match constant part and ending digits
var matchstart = Regex.Match(start,#"^(.*?)(\d+)$");
int numberstart = int.Parse(matchstart.Groups[2].Value);
var matchend = Regex.Match(end,#"^(.*?)(\d+)$");
int numberend = int.Parse(matchend.Groups[2].Value);
// constant parts must be the same
if (matchstart.Groups[1].Value != matchend.Groups[1].Value)
throw new ArgumentException("");
// create a format string with same number of digits as original
string format = new string('0', matchstart.Groups[2].Length);
for (int ii = numberstart; ii <= numberend; ++ii)
Console.WriteLine(matchstart.Groups[1].Value + ii.ToString(format));
You could use a Regex:
var match=Regex.Match("Super_Confusing-String#w00t0003",#"(?<=(^.*\D)|^)\d+$");
if(match.Success)
{
var val=int.Parse(match.Value);
Console.WriteLine(val);
}
To answer more specifically, you could use named groups to extract what you need:
var match=Regex.Match(
"Super_Confusing-String#w00t0003",
#"(?<prefix>(^.*\D)|^)(?<digits>\d+)$");
if(match.Success)
{
var prefix=match.Groups["prefix"].Value;
Console.WriteLine(prefix);
var val=int.Parse(match.Groups["digits"].Value);
Console.WriteLine(val);
}
If you can assume that the last 5 characters are the number then:
string prefix = "myprefix-";
for (int i=1; i <=23; i++)
{
Console.WriteLine(myPrefix+i.ToString("D5"));
}
This function will find the trailing number.
private int FindTrailingNumber(string str)
{
string numString = "";
int numTest;
for (int i = str.Length - 1; i > 0; i--)
{
char c = str[i];
if (int.TryParse(c.ToString(), out numTest))
{
numString = c + numString;
}
}
return int.Parse(numString);
}
Assuming all your base strings are the same, this would iterate between strings.
string s1 = "asdf123";
string s2 = "asdf127";
int num1 = FindTrailingNumber(s1);
int num2 = FindTrailingNumber(s2);
string strBase = s1.Replace(num1.ToString(), "");
for (int i = num1; i <= num2; i++)
{
Console.WriteLine(strBase + i.ToString());
}
I think it would be better if you do the search from the last (Rick already upvoted you since it was ur logic :-))
static void Main(string[] args)
{
var s = "IAmAString-00001";
int index = -1;
for (int i = s.Length - 1; i >=0; i--)
{
if (!char.IsDigit(s[i]))
{
index = i;
break;
}
}
if (index == -1)
Console.WriteLine("digits not found");
else
Console.WriteLine("digits: {0}", s.Substring(index));
Console.ReadKey();
}
HTH
If the last X numbers are always digits, then:
int x = 5;
string s = "IAmAString-00001";
int num = int.Parse(s.Substring(s.Length - x, x));
Console.WriteLine("Your Number is: {0}", num);
If the last digits can be 3, 4, or 5 in length, then you will need a little more logic:
int x = 0;
string s = "IAmAString-00001";
foreach (char c in s.Reverse())//Use Reverse() so you start with digits only.
{
if(char.IsDigit(c) == false)
break;//If we start hitting non-digit characters, then exit the loop.
++x;
}
int num = int.Parse(s.Substring(s.Length - x, x));
Console.WriteLine("Your Number is: {0}", num);
I'm not good with complicated RegEx. Because of this, I always shy away from it when maximum optimization is unnecessary. The reason for this is RegEx doesn't always parse strings the way you expect it to. If there is and alternate solution that will still run fast then I'd rather go that route as it's easier for me to understand and know that it will work with any combination of strings.
For Example: if you use some of the other solutions presented here with a string like "I2AmAString-000001", then you will get "2000001" as your number instead of "1".
i know how to make a console read two integers but each integer by it self like this
int a = int.Parse(Console.ReadLine());
int b = int.Parse(Console.ReadLine());
if i entered two numbers, i.e (1 2), the value (1 2), cant be parse to integers
what i want is if i entered 1 2 then it will take it as two integers
One option would be to accept a single line of input as a string and then process it.
For example:
//Read line, and split it by whitespace into an array of strings
string[] tokens = Console.ReadLine().Split();
//Parse element 0
int a = int.Parse(tokens[0]);
//Parse element 1
int b = int.Parse(tokens[1]);
One issue with this approach is that it will fail (by throwing an IndexOutOfRangeException/ FormatException) if the user does not enter the text in the expected format. If this is possible, you will have to validate the input.
For example, with regular expressions:
string line = Console.ReadLine();
// If the line consists of a sequence of digits, followed by whitespaces,
// followed by another sequence of digits (doesn't handle overflows)
if(new Regex(#"^\d+\s+\d+$").IsMatch(line))
{
... // Valid: process input
}
else
{
... // Invalid input
}
Alternatively:
Verify that the input splits into exactly 2 strings.
Use int.TryParse to attempt to parse the strings into numbers.
You need something like (no error-checking code)
var ints = Console
.ReadLine()
.Split()
.Select(int.Parse);
This reads a line, splits on whitespace and parses the split strings as integers. Of course in reality you would want to check if the entered strings are in fact valid integers (int.TryParse).
Then you should first store it in a string and then split it using the space as token.
Read the line into a string, split the string, and then parse the elements. A simple version (which needs to have error checking added to it) would be:
string s = Console.ReadLine();
string[] values = s.Split(' ');
int a = int.Parse(values[0]);
int b = int.Parse(values[1]);
string[] values = Console.ReadLine().Split(' ');
int x = int.Parse(values[0]);
int y = int.Parse(values[1]);
in 1 line, thanks to LinQ and regular expression (no type-checking neeeded)
var numbers = from Match number in new Regex(#"\d+").Matches(Console.ReadLine())
select int.Parse(number.Value);
string x;
int m;
int n;
Console.WriteLine("Enter two no's seperated by space: ");
x = Console.ReadLine();
m = Convert.ToInt32(x.Split(' ')[0]);
n = Convert.ToInt32(x.Split(' ')[1]);
Console.WriteLine("" + m + " " + n);
This Should work as per your need!
public static class ConsoleInput
{
public static IEnumerable<int> ReadInts()
{
return SplitInput(Console.ReadLine()).Select(int.Parse);
}
private static IEnumerable<string> SplitInput(string input)
{
return Regex.Split(input, #"\s+")
.Where(x => !string.IsNullOrWhiteSpace(x));
}
}
int a, b;
string line = Console.ReadLine();
string[] numbers= line.Split(' ');
a = int.Parse(numbers[0]);
b = int.Parse(numbers[1]);
Try this:
string numbers= Console.ReadLine();
string[] myNumbers = numbers.Split(' ');
int[] myInts = new int[myNumbers.Length];
for (int i = 0; i<myInts.Length; i++)
{
string myString=myNumbers[i].Trim();
myInts[i] = int.Parse(myString);
}
Hope it helps:)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SortInSubSet
{
class Program
{
static int N, K;
static Dictionary<int, int> dicElements = new Dictionary<int, int>();
static void Main(string[] args)
{
while (!ReadNK())
{
Console.WriteLine("***************** PLEASE RETRY*********************");
}
var sortedDict = from entry in dicElements orderby entry.Key/3 , entry.Value ascending select entry.Value;
foreach (int ele in sortedDict)
{
Console.Write(ele.ToString() + " ");
}
Console.ReadKey();
}
static bool ReadNK()
{
dicElements = new Dictionary<int, int>();
Console.WriteLine("Please entere the No. of element 'N' ( Between 2 and 9999) and Subset Size 'K' Separated by space.");
string[] NK = Console.ReadLine().Split();
if (NK.Length != 2)
{
Console.WriteLine("Please enter N and K values correctly.");
return false;
}
if (int.TryParse(NK[0], out N))
{
if (N < 2 || N > 9999)
{
Console.WriteLine("Value of 'N' Should be Between 2 and 9999.");
return false;
}
}
else
{
Console.WriteLine("Invalid number: Value of 'N' Should be greater than 1 and lessthan 10000.");
return false;
}
if (int.TryParse(NK[1], out K))
{
Console.WriteLine("Enter all elements Separated by space.");
string[] kElements = Console.ReadLine().Split();
for (int i = 0; i < kElements.Length; i++)
{
int ele;
if (int.TryParse(kElements[i], out ele))
{
if (ele < -99999 || ele > 99999)
{
Console.WriteLine("Invalid Range( " + kElements[i] + "): Element value should be Between -99999 and 99999.");
return false;
}
dicElements.Add(i, ele);
}
else
{
Console.WriteLine("Invalid number( " + kElements[i] + "): Element value should be Between -99999 and 99999.");
return false;
}
}
}
else
{
Console.WriteLine(" Invalid number ,Value of 'K'.");
return false;
}
return true;
}
}
}
I have a much simpler solution, use a switch statement and write a message for the user in each case, using the Console.write() starting with a ("\n").
Here's an example of filling out an array with a for loop while taking user input. * Note: that you don't need to write a for loop for this to work*
Try this example with an integer array called arrayOfNumbers[] and a temp integer variable. Run this code in a separate console application and Watch how you can take user input on the same line!
int temp=0;
int[] arrayOfNumbers = new int[5];
for (int i = 0; i < arrayOfNumbers.Length; i++)
{
switch (i + 1)
{
case 1:
Console.Write("\nEnter First number: ");
//notice the "\n" at the start of the string
break;
case 2:
Console.Write("\nEnter Second number: ");
break;
case 3:
Console.Write("\nEnter Third number: ");
break;
case 4:
Console.Write("\nEnter Fourth number: ");
break;
case 5:
Console.Write("\nEnter Fifth number: ");
break;
} // end of switch
temp = Int32.Parse(Console.ReadLine()); // convert
arrayOfNumbers[i] = temp; // filling the array
}// end of for loop
The magic trick here is that you're fooling the console application, the secret is that you're taking user input on the same line you're writing your prompt message on. (message=>"Enter First Number: ")
This makes user input look like is being inserted on the same line. I admit it's a bit primitive but it does what you need without having to waste your time with complicated code for a such a simple task.