Counting words and sum digits why doesnt it work? - c#

Task:
The program asks the user to enter the text, after entering the text, the program declares how many words are in the text. It also counts the amount of digits in the text and displays it on the screen.
static void Main(string[] args)
{
Console.Write("Insert text: ");
string s = Console.ReadLine();
int count = 1, num, sum = 0, r;
for (int i = 1; i < s.Length; i++)
{
if (Char.IsWhiteSpace(s[i]))
{
count++;
}
}
num = int.Parse(Console.ReadLine());
while (num != 0)
{
r = num % 10;
num = num / 10;
sum = sum + r;
}
Console.WriteLine("Sum of Digits of the Number : " + sum);
Console.WriteLine("In text {1} names", s, count);
}
The program asks for the text and numbers to be entered. The numbers in the text are counted why doesnt it work correctly?

As per the input/output described in the comment, You do not need a second ReadLine Statement. You can do as follows.
static void Main(string[] args)
{
Console.WriteLine("Enter Text");
var userEntry = Console.ReadLine();
var countOfWords = userEntry.Split(new []{" "},StringSplitOptions.RemoveEmptyEntries).Count();
var sum = userEntry.Where(c => Char.IsDigit(c)).Select(x=>int.Parse(x.ToString())).Sum();
Console.WriteLine($"Count Of Words :{countOfWords}{Environment.NewLine}Sum :{sum}");
}
This is in the case when(as per your comment), the input string is "xsad8 dlas8 dsao9", for which the sum would be 25.
If the input string is "xsad8 dlas81 dsao9" and you want to treat 81 as '81', rather than 8 & 1, the Sum can be calculated as follows.
var sum = Regex.Split(userEntry, #"\D+").Where(s => s != String.Empty).Sum(x=>int.Parse(x));
Sum in above case would be 98

Try this code. I hope it will help you.
using System;
namespace SimpleProblem
{
class Program
{
static void Main(string[] args)
{
// Task:
// The program asks the user to enter the text, after
// entering the text, the program declares how many words
// are in the text. It also counts the amount of digits in
// the text and displays it on the screen.
Console.WriteLine("Enter a Text");
string word = Console.ReadLine();
int wordCount = 0;
char[] wordsArray = word.ToCharArray();
foreach (var item in wordsArray)
{
//Counting the number of words in array.
wordCount = wordCount + 1;
}
Console.WriteLine("Entered Text: " + word);
Console.WriteLine("No. of Counts: " + wordCount);
}
}
}

Related

How can I write a program that will take the input of three numbers and print the sum on the console?

So basically my question is how I can write a program that will take the input of three numbers and display the sum on console?
I tried a few solutions and I watched a couple of Youtube videos, but still didn't quite understand.
Here is an example how you can read the input from the console, convert it to an integer, calculate the sum, and then display the result in the console.
static void Main(string[] args)
{
Console.WriteLine("Enter the first number: "); // Prints "Enter the first number:" in the console.
var number1string = Console.ReadLine(); // Reads the input which the user supplies. This is a string.
Console.WriteLine("Enter the second number: ");
var number2string = Console.ReadLine();
Console.WriteLine("Enter the third number: ");
var number3string = Console.ReadLine();
var number1 = int.Parse(number1string); // Convert the string from the user to an integer value
var number2 = int.Parse(number2string);
var number3 = int.Parse(number3string);
var sum = number1 + number2 + number3; // Calculate the sum of the 3 inputs
Console.WriteLine($"The sum of {number1}, {number2} and {number3} is: {sum}"); // Show the result in the console.
}
If this is not homework and not passing values into the app but instead prompting for values consider the following code which by installing Spectre.Console NuGet package provides a method to get numbers with validation.
In the code below TextPrompt<int> means to get an int, if you want a double TextPrompt<double> etc.
using System;
using System.Collections.Generic;
using System.Linq;
using Spectre.Console;
namespace YourNamespaceGoesHere
{
partial class Program
{
static void Main(string[] args)
{
string[] prompts =
{
"first",
"second",
"third"
};
List<int> list = new List<int>();
for (int index = 0; index < 3; index++)
{
int value = AnsiConsole.Prompt(
new TextPrompt<int>($"[cyan]Enter {prompts[index]} number[/]")
.PromptStyle("yellow")
.ValidationErrorMessage("[white on red]Please enter a number[/]")
.DefaultValue(0)); ;
list.Add(value);
Console.Clear();
}
AnsiConsole.MarkupLine($"[white on blue]Total is {list.Sum()}[/]");
Console.ReadLine();
}
}
}
If using a library is not for you than consider the following where if the value entered is not a number the value is 0.
static void Main(string[] args)
{
string[] prompts =
{
"first",
"second",
"third"
};
List<int> list = new List<int>();
for (int index = 0; index < 3; index++)
{
Console.WriteLine($"Enter {prompts[index]} number");
var userValue = Console.ReadLine();
if (int.TryParse(userValue, out var value))
{
list.Add(value);
}
Console.Clear();
}
Console.WriteLine($"Total is {list.Sum()}");
Console.ReadLine();
}
Finally, for either solution to see the values entered Console.WriteLine(string.Join(",", list));
// Paste that into your program.cs (dotnet 6)
// See https://aka.ms/new-console-template for more information
Console.WriteLine("Hello, World!");
var lineString = Console.ReadLine();
// lineString could be "123 456 789"
// now we split the numbers into an array
if (lineString != null && lineString.Length > 0)
{
var splittedNumbers = lineString.Split();
// splittedNumbers will look like:
// splittedNumbers[0] -> 123
// splittedNumbers[1] -> 456
// splittedNumbers[2] -> 789
// now we need to transform the string into an number and add summarize it
var sumNumber = 0;
foreach (var split in splittedNumbers)
{
var number = 0;
// try to parse your input if possible - without throwing an arror
int.TryParse(split, out number);
sumNumber += number;
}
Console.WriteLine("Your sum: " + sumNumber.ToString());
}
// Append that to let the console not quid directly without sseing the sum....
Console.ReadLine();

How to Make User Input into Array and Pass It to a Method in C#?

So I have this very simple program that I have created that gets the user input and then pass the values to the method named average. Everything is perfectly fine, however, something crossed my mind like "What if the user only enters two numbers or an array of numbers?". I know that I have to use array as a parameter, but somehow I am not sure how to accomplish what i want to do. Do you guys have any tips on how I can achieve what i am trying to do? My code is here:
using System;
namespace Averages
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter number(s): ");
double num1 = Convert.ToInt32(Console.ReadLine());
double num2 = Convert.ToInt32(Console.ReadLine());
double num3 = Convert.ToInt32(Console.ReadLine());
average(num1, num2, num3);
Console.ReadKey();
}
static void average(double num1, double num2, double num3)
{
double avg = (num1 + num2 + num3) / 3;
Console.WriteLine("You have entered: " + num1 + ", " + num2 + ", " + num3);
Console.WriteLine("The average is: " + avg);
}
}
}
I would appreciate any help. Thank you!
you can ask user for input of comma delimited numbers. Or, you can repeat input until user enters something like 0. I that case, you can change your program into this:
using System;
using System.Collections.Generic;
using System.Linq;
namespace Averages
{
class Program
{
static void Main(string[] args)
{
//list to hold your numbers, way more flexible than array
List<double> enteredNubers = new List<double>();
//message user
Console.WriteLine("Enter number(s) or 0 to end: ");
//run this block of code indefinitely
while (true)
{
//take user input
string userinput = Console.ReadLine().Trim();
//if user enters 0, exit this loop
if (userinput == "0")
break;
double num;
//try to convert text to number
if (double.TryParse(userinput, out num))
{
//if it is successful, add number to list
enteredNubers.Add(num);
}
else //else message user with error
Console.WriteLine("Wrong input. Please enter number or 0 to end");
}
//when loop is exited (when user entered 0), call method that calculates average
Average(enteredNubers);
Console.ReadKey();
}
static void Average(List<double> numbers)
{
double sum = 0;
//go through list and add each number to sum
foreach (double num in numbers)
{
sum += num;
}
//or, you can sum it using linq like this:
//sum = numbers.Sum();
//or you can even calculate average by calling Average method on list, like numbers. Average();
//show message - all the entered numbers, separated by comma
Console.WriteLine("You have entered: " + string.Join(", ", numbers.ToArray()));
//write average
Console.WriteLine("The average is: " + sum/numbers.Count);
}
}
}
Let's solve the problem step by step. First we want to add a single double:
private static bool ReadDouble(out double value) {
value = 0.0;
while (true) {
Console.WriteLine("Enter number or X to exit:");
string input = Console.ReadLine().Trim();
if (input == "X" || input == "x")
return false;
else if (double.TryParse(input, out value))
return true;
Console.Write("Syntax error, please, try again.");
}
}
Now we are ready to read arbitrary number of values. Since we don't know the number, List<double> is a better choice than double[]
using System.Collections.Generic;
...
private static List<double> ReadDoubles() {
List<double> result = new List<double>();
while (ReadDouble(out var value))
result.Add(value);
return result;
}
Finally, we want to compute average
static void Main(string[] args) {
List<double> list = ReadDoubles();
if (list.Count <= 0)
Console.WriteLine("Empty list: no average");
else {
double sum = 0.0;
foreach (double item in list)
sum += item;
double avg = sum / list.Count;
Console.Write("The average is: " + avg);
}
}
However, you can do it in just few lines via Linq:
using System.Collections.Generic;
using System.Collections.Linq;
...
static void Main(string[] args) {
Console.WriteLine("Enter numbers separated by spaces, e.g. 1 2 3 15");
double avg = Console
.ReadLine()
.Split(new char[] { ' '}, StringSplitOptions.RemoveEmptyEntries)
.Select(item => double.Parse(item))
.Average();
Console.Write($"The average is: {avg}");
}
Here Update your methods Accordingly
static void Main(string[] args)
{
Console.WriteLine("Type Exit to stop the program... \nEnter number");
List<double> doubleList = new List<double>();
string input = Console.ReadLine();
double d;
while(!input.Equals("Exit"))
{
if(String.IsNullOrEmpty(input) || !Double.TryParse(input,out d))
{
break;
}
doubleList.Add(d);
input = Console.ReadLine();
}
average(doubleList);
Console.ReadKey();
}
static void average(List<double> doubleData)
{
double total = 0;
foreach (double number in doubleData)
{
total += number;
}
Console.WriteLine("Average = " + total/doubleData.Count);
}
Something like the following should meet your needs:
string stopLine = "STOP";
List<double> lines = new List<double>();
string line;
while ((line = Console.ReadLine()) != stopLine) {
lines.Add(Convert.ToDouble(line));
}
Average(lines);
Console.ReadLine();
Now your average method becomes
private static void Average(List<double> lines) {
Console.WriteLine(lines.Average());
}
Note that you should handle the case where the input is not a number.
static void Main(string[] args)
{
Console.WriteLine("Enter number(s): ");
string input = "";
List<double> doubleList = new List<double>();
while (input != "q")
{
input = Console.ReadLine();
if(input != "q")
{
try
{
doubleList.Add(Convert.ToInt32(input));
}
catch
{
Console.WriteLine("Invalid input");
}
}
}
average(doubleList);
Console.ReadKey();
}
static void average(List<double> myList)
{
double sum = 0;
Console.Write("You have entered: ")
foreach (int element in myList)
{
sum += element;
Console.Write(element + ", ");
}
Console.WriteLine("");
double avg = sum / myList.Count;
Console.WriteLine("The average is: " + avg);
}
static void Main(string[] args)
{
var numbers = new List<double>();
Console.WriteLine("Enter the three numbers, one per line");
for (var i = 0; i < 3; ++i)
{
while (true)
{
if (double.TryParse(Console.ReadLine(), out var enteredNumber))
{
//the number is a number, so...
numbers.Add(enteredNumber);
break;
}
//if not a number...
Console.WriteLine("That's not a number, try again");
}
}
Average(numbers);
Console.ReadKey();
}
static void Average(IEnumerable<double> numbers)
{
var average = numbers.Average();
Console.Write("You have entered: ");
foreach (var num in numbers)
{
Console.Write($" {num} ");
}
Console.WriteLine(String.Empty);
Console.WriteLine("The average is: " + average);
}
In general, Lists are better than Arrays for this kind of thing; List's are stretchy, Arrays are not. If you want this to work with 4 (or 200) numbers, all you have to do is change the for loop's bounds.
I'm using double.TryParse, this way I can let the user correct a badly entered number (always assume users will enter bad data). I'm passing the collection of numbers to the average function as an IEnumerable and not a List (the Average function is hardly needed (note that the calculation of the average is just an extension method on collections of numerics) but you had one, so I included it. An IEnumerable cannot be changed by the called function, so it's more appropriate here (and, all lists (and all arrays, for that matter) are enumerable).
Looking at all these fancy answers,i guess people are forgetting the basics of programming.
The OP literally states using arrays and instead of that you all are pushing him into hard to read code. The guy is trying to learn the basics which obviously no one cares to learn about.
Dear Cyrus don't get into generics right away. I would suggest that you stick to arrays for a while.
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter number(s): ");
double[] values = new double[3]; //initialize double array with its size
for (int i = 0; i < values.Length; i++)
{
//iterate through the array and assign value to each index of it.
values[i]=Convert.ToDouble(Console.ReadLine());
}
average(values);
Console.ReadKey();
}
//set method that accepts double array as parameter
static void average(double[] values)
{
double average =0;// declare var that will hold the sum of numbers
int length = values.Length;//get array length, use it to divide the summation of numbers
Console.WriteLine("You have entered: ");
for (int i = 0; i < values.Length; i++)
{
//also display the numbers if you need to
Console.WriteLine(values[i]);
//iterate through each value in the array and sum it up.
average = values[i] + average;
}
//divide the sum of numbers by the length of array
Console.WriteLine("The average is: " + (average/length));
}
}
You can also dynamically set the length of the array by letting the user input its length, just play with code and let your imagination loose. Happy coding!
You have a couple options. Either ask for the user input to be delimited somehow. For example a comma delimited user input would be"1, 2, 3, 4". You've then got to worry about parsing that and ensuring the user entered valid input.
Another option is to have a while loop that has Console.ReadLine() within, and you only exit the loop when the user enters a pre-determined exit word (such as "stop" or exit")
static void Main(string[] args)
{
var inputValues = new List<double>();
while (true)
{
var input = Console.ReadLine();
if (input.Equals("stop", StringComparison.InvariantCultureIgnoreCase))
break;
if (double.TryParse(input, out double inputValue))
{
inputValues.Add(inputValue);
}
else
{
Console.WriteLine("Invalid input!");
}
}
PrintAverage(inputValues);
Console.ReadKey();
}
static void PrintAverage(IEnumerable<double> values)
{
Console.WriteLine("You have entered: {0}", string.Join(", ", values));
Console.WriteLine("The average is: {0}", values.Average());
}
Here I've opted for the second option. It'll continuously loop until the input is stop. It will also now try parse the value rather than directly convert, and will print a warning message if the parse failed.
If the parse was successful it's added to our inputValues collection. Once out of the while loop, we pass the collection to PrintAverage - a method that takes an IEnumerable<double> (could be one value, 100 values, or no values). Because List implements IEnumerable, we can pass our list to this method. IEnumerable has an Average() method built-in.

Getting User Input and Adding it to an array at C#

I am trying to get input from user 5 times and add those values to marks array;
Then, it will calculate the average and print positive or negative accordingly. However, I can not take input from the user it just prints "Enter 5 elements". After getting input from user how can I add them to marks array? Any tips would be helpful.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
double average =0;
int [] marks = new int[] { };
for (int a = 0; a < 5; a++){
Console.WriteLine("Enter 5 elements:");
string line = Console.ReadLine();
Console.WriteLine(line);
}
for (int i = 0; i < marks.Length; i++){
average = marks.Average();
}
if(average>0){
Console.WriteLine("Positive");
}else{
Console.WriteLine("Negative");
}
}
}
I would use a while loop combined with int.TryParse to check if the user input is a number. Also it doesn't make any sense to put average = marks.Average(); inside a for loop, because LINQ Average calculates the average of a collection (in your case the marks array).
static void Main()
{
int[] marks = new int[5];
int a = 0;
Console.WriteLine("Enter 5 elements:");
while (a < 5)
{
if (int.TryParse(Console.ReadLine(), out marks[a]))
a++;
else
Console.WriteLine("You didn't enter a number! Please enter again!");
}
double average = marks.Average();
if (average > 0)
Console.WriteLine("Positive");
else
Console.WriteLine("Negative");
}
DEMO HERE
Edited my answer to illustrate solving your problem without a for loop.
class Program
{
const int numberOfMarks = 5;
static void Main()
{
List<int> marks = new List<int>();
Enumerable.Range(1, numberOfMarks)
.ForEach((i) => {
Console.Write($"Enter element {i}:");
marks.Add(int.TryParse(Console.ReadLine(), out var valueRead) ? valueRead : 0);
Console.WriteLine($" {valueRead}");
});
Console.WriteLine(marks.Average() >= 0 ? "Positive" : "Negative");
}
}
This will help you, just copy and paste it.
There are some explanation with comments.
class Program
{
static void Main()
{
const int numberOfMarks = 5;
int[] marks = new int[numberOfMarks];
Console.WriteLine("Enter 5 elements:");
for (int a = 0; a < numberOfMarks; a++)
{
// If entered character not a number, give a chance to try again till number not entered
while(!int.TryParse(Console.ReadLine(), out marks[a]))
{
Console.WriteLine("Entered not a character");
}
Console.WriteLine("You entered : " + marks[a]);
}
// Have to call Average only once.
var avg = marks.Average();
Console.WriteLine(avg > 0 ? "Positive average" : "Negative average");
Console.ReadLine();
}
}
Follow Stackoverflow Answer
since integer array is being used, and as input from the console is a string value, you need to convert it using Parse() Method. For e.g.
string words = "83";
int number = int.Parse(words);
Edit: using string variable in parsing.

int not what I try and assign it

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;
}
}
}

reading two integers in one line using C#

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.

Categories