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.
Related
I'm trying to creat an algorithm who receive a list of user-defined size (dynamic list) but i keep having unhandled exceptions when trying to implement the algorithm.
The cleanest i found was this
using System.Linq;
using System.Collections.Generic;
static void Sorter()
{
Console.WriteLine("Write the number of words the dictionary will have");
int Size = Convert.ToInt32(Console.ReadLine());
int ListEnd = Size;
List<string?> wordList = new() {};
while (Size>0)
{
Console.WriteLine("Write a term A");
string? item1 = "" ?? "1";
item1 = Console.ReadLine();
wordList.Add(item1);
Size--;
}
Console.WriteLine($"{wordList.Count()} terms");
Console.WriteLine(string.Join(" ", wordList));
string? last = wordList[ListEnd];
wordList.Sort();
Console.WriteLine(string.Join(" ", wordList));
}
I want the program to receive all the unsorted names written by the user and then reposition then in the List in a alphabetically sorted way.
First of all, if you want to declare an empty list, you can do it with:
List<string?> wordList = new List<string?>();
Then, A namespace cannot directly contain members such as fields or methods. Thats why you need to wrap the function by a class:
public class AnyClassName
{
static void Sorter()
{
Console.WriteLine("Write the number of words the dictionary will have");
int Size = Convert.ToInt32(Console.ReadLine());
int ListEnd = Size - 1;
List<string?> wordList = new List<string?>();
while (Size>0)
{
Console.WriteLine("Write a term A");
string? item1 = "" ?? "1";
item1 = Console.ReadLine();
wordList.Add(item1);
Size--;
}
Console.WriteLine($"{wordList.Count()} terms");
Console.WriteLine(string.Join(" ", wordList));
string? last = wordList[ListEnd];
wordList.Sort();
Console.WriteLine(string.Join(" ", wordList));
}
}
Then, you need to call the function in main function:
using System;
using System.Linq;
using System.Collections.Generic;
public class AnyClassName
{
static void Sorter()
{
Console.WriteLine("Write the number of words the dictionary will have");
int Size = Convert.ToInt32(Console.ReadLine());
int ListEnd = Size - 1;
List<string?> wordList = new List<string?>();
while (Size>0)
{
Console.WriteLine("Write a term A");
string? item1 = "" ?? "1";
item1 = Console.ReadLine();
wordList.Add(item1);
Size--;
}
Console.WriteLine($"{wordList.Count()} terms");
Console.WriteLine(string.Join(" ", wordList));
string? last = wordList[ListEnd];
wordList.Sort();
Console.WriteLine(string.Join(" ", wordList));
}
public static void Main(string[] args)
{
Sorter();
}
}
A couple pointers, as pointed out in the comments of your original post (pun not intended):
Try to include any errors when stating that you are seeing errors.
Try to specify what you are actually looking for. Are you looking for a cleaner implementation? Are you looking for a fix to an error (if so, refer to the previous pointer)?
As for the direct answer to your question, I am assuming that you are looking for a cleaner implementation that doesn't result in errors during compilation. Here we go:
using static System.Int32;
List<string> ReadStringsFromConsole()
{
int numWords = 0;
string word = string.Empty;
List<string> words = new();
// Keep on reading until we get a valid number
while (numWords < 1)
{
Console.Clear();
Console.Write("How many words would you like to enter? ");
bool unused = TryParse(Console.ReadLine(), out numWords); // TryParse to make sure we don't get an exception
}
// Keep on reading until we get a valid word, at which point it is added to the list
// numWords is only decremented if we were able to successfully add the word to the list
do
{
Console.Clear();
Console.Write("Enter a word: ");
word = Console.ReadLine() ?? string.Empty;
if (word == string.Empty) continue;
words.Add(word);
numWords--;
} while (numWords > 0 && word != string.Empty);
words.Sort();
return words;
}
List<string> words = ReadStringsFromConsole();
Console.WriteLine(string.Join(" ", words));
Console.ReadKey();
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
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.
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;
}
}
}
I am a beginner in .net and I made a simple console application and it's works. My problem is when I give input the input must be in new line
eg:
1
2
3
how I input like
1 2
3
I am using the following code
int a, b, c,d;
Console.WriteLine("Enter the numbers:");
a = Convert.ToInt32(Console.ReadLine());
b = Convert.ToInt32(Console.ReadLine());
c = Convert.ToInt32(Console.ReadLine());
d = a + b + c;
Console.WriteLine("Sum:" + d);
Write an input parser... ReadLine, split the resulting string by space character and feed each segment into int converter and sum them.
Example given below is taking advantage of Linq which is a bit functional and allow chaining something like the token array resulting from the split and performs operations on each of its elements. I.e. Select(...) is basically a map function that will apply Convert.ToInt32 to each elements in the token array and then pipe that into the Aggregate function that memoize the result so far (starting from 0 and keep adding the next element in the now converted int token array ... represented by s + t where s is current memoized seed and t is the current token in the iteration.)
using System;
using System.Linq;
public class Program
{
public static void Main()
{
var str = Console.ReadLine();
var tokens = str.Split(' ');
var result = tokens.Select(t => Convert.ToInt32(t)).Aggregate(0, (s, t) => s + t);
Console.WriteLine(result);
}
}
For completeness sake... This second version should be more resistant to error:
using System;
using System.Linq;
public class Program
{
public static void Main()
{
Console.WriteLine("Enter 1 or more numbers separated by space in between. I.e. 1 2\nAny non numerical will be treated as 0:");
var str = Console.ReadLine();
if (string.IsNullOrWhiteSpace(str))
{
Console.WriteLine("Sorry, expecting 1 or more numbers separated by space in betwen. I.e. 5 6 8 9");
}
else
{
var tokens = str.Split(' ');
var result = tokens
.Select(t =>
{
int i;
if (int.TryParse(t, out i))
{
Console.WriteLine("Valid Number Detected: {0}", i);
};
return i;
})
.Aggregate(0, (s, t) => s + t);
Console.WriteLine("Sum of all numbers is {0}", result);
}
Console.ReadLine();
}
}
You are using Console.ReadLine() which reads the whole line.
Documentation:
A line is defined as a sequence of characters followed by a carriage return (hexadecimal 0x000d), a line feed (hexadecimal 0x000a), or the value of the Environment.NewLine property. The returned string does not contain the terminating character(s).
You can read whole line and then process it, for example with String.Split method.
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
//1 2
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.
Here's an exmaple :
class Program
{
private static void Main(string[] args)
{
int a = 0,
b = 0;
Console.WriteLine("Enter the numbers:");
var readLine = Console.ReadLine();
if (readLine != null)
{
// 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(readLine))
{
string[] tokens = readLine.Split();
//Parse element 0
a = int.Parse(tokens[0]);
//Parse element 1
b = int.Parse(tokens[1]);
}
else
{
Console.WriteLine("Please enter numbers");
}
}
var c = Convert.ToInt32(Console.ReadLine());
var d = a + b + c;
Console.WriteLine("Sum:" + d);
}
}