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);
}
}
Related
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();
Explanation: The task itself is that we have 13 strings (stored in the sor[] array) like the one in the title or 'EEENKDDDDKKKNNKDK'
and we have to shorten it in a way that if there's two or more of the same letter next to eachother then we have to write it in the form of 'NumberoflettersLetter'
So by this rule, 'EEENKDDDDKKKNNKDK' would become '3ENK4D3K2NKDK'
using System;
public class Program
{
public static void Main(string[] args)
{
string[] sor = new string[] { "EEENKDDDDKKKNNKDK", "'EEDDDNE'" };
char holder;
int counter = 0;
string temporary;
int indexholder;
for (int i = 0; i < sor.Length; i++)
{
for (int q = 0; q < sor[i].Length; q++)
{
holder = sor[i][q];
indexholder = q;
counter = 0;
while (sor[i][q] == holder)
{
q++;
counter++;
}
if (counter > 1)
{
temporary = Convert.ToString(counter) + holder;
sor[i].Replace(sor[i].Substring(indexholder, q), temporary); // EX here
}
}
}
Console.ReadLine();
}
}
Sorry I didn't make the error clear, it says that :
"The value of index and length has to represent a place inside the string (System.ArgumentOutOfRangeException) - name of parameter: length"
...but I have no clue what's wrong with it, maybe it's a tiny little mistake, maybe the whole thing is messed up, so this is why I'd like someone to help me with this D:
(Ps 'indexholder' is there because i need it for another exercise)
EDIT:
'sor' is the string array that holds these strings (there are 13 of them) like the one mentioned in the title or in the example
You can use regex for this:
Regex.Replace("EEENKDDDDKKKNNKDK", #"(.)\1+", m => $"{m.Length}{m.Groups[1].Value}")
Explanation:
(.) matches any character and puts it in group #1
\1+ matches group #1 as many times can it can
Shortening the same string inplace is more difficult then construction a new one while iterating the old one char by char. If you plan to iteratively add to a string it is better to use the StringBuilder - class instead of adding directly to a string (performance reasons).
You can streamline your approach by using IEnumerable.Aggregate function wich does the iteration on one string for you automatically:
using System;
using System.Linq;
using System.Text;
public class Program
{
public static string RunLengthEncode(string s)
{
if (string.IsNullOrEmpty(s)) // avoid null ref ex and do simple case
return "";
// we need a "state" between the differenc chars of s that we store here:
char curr_c = s[0]; // our current char, we start with the 1st one
int count = 0; // our char counter, we start with 0 as it will be
// incremented as soon as it is processed by Aggregate
// ( and then incremented to 1)
var agg = s.Aggregate(new StringBuilder(), (acc, c) => // StringBuilder
// performs better for multiple string-"additions" then string itself
{
if (c == curr_c)
count++; // same char, increment
else
{
// other char
if (count > 1) // store count if > 1
acc.AppendFormat("{0}", count);
acc.Append(curr_c); // store char
curr_c = c; // set current char to new one
count = 1; // startcount now is 1
}
return acc;
});
// add last things
if (count > 1) // store count if > 1
agg.AppendFormat("{0}", count);
agg.Append(curr_c); // store char
return agg.ToString(); // return the "simple" string
}
Test with
public static void Main(string[] args)
{
Console.WriteLine(RunLengthEncode("'EEENKDDDDKKKNNKDK' "));
Console.ReadLine();
}
}
Output for "'EEENKDDDDKKKNNKDK' ":
'3ENK4D3K2NKDK'
Your approach without using the same string is more like this:
var data = "'EEENKDDDDKKKNNKDK' ";
char curr_c = '\x0'; // avoid unasssinged warning
int count = 0; // counter for the curr_c occurences in row
string result = string.Empty; // resulting string
foreach (var c in data) // process every character of data in order
{
if (c != curr_c) // new character found
{
if (count > 1) // more then 1, add count as string and the char
result += Convert.ToString(count) + curr_c;
else if (count > 0) // avoid initial `\x0` being put into string
result += curr_c;
curr_c = c; // remember new character
count = 1; // so far we found this one
}
else
count++; // not new, increment counter
}
// add the last counted char as well
if (count > 1)
result += Convert.ToString(count) + curr_c;
else
result += curr_c;
// output
Console.WriteLine(data + " ==> " + result);
Output:
'EEENKDDDDKKKNNKDK' ==> '3ENK4D3K2NKDK'
Instead of using the indexing operator [] on your string and have to struggle with indexes all over I use foreach c in "sometext" ... which will proceed char-wise through the string - much less hassle.
If you need to run-length encode an array/list (your sor) of strings, simply apply the code to each one (preferably by using foreach s in yourStringList ....
Hello friends i am a total beginner in c#.
I want to read numbers in the following format
2
1 10
3 5
For reading 2 i have used Convert.ToInt32(Console.ReadLine()) method and successfully stored it. But for the next input i want to read the number and after a space i want to read another number. I cannot use ReadLine() method.. I have used Convert.ToInt32(Console.Read())
But the number 1 is read as 49
So How do i achieve reading numbers
In java i have found a similar class called Scanner which contains methods line nextInt()
Is there any C# equivalent to that class.
In short i just want to know how to read and store numbers(integers or floats) in C#.
You can use ReadLine() and just split on whitespace, i.e.,
void Main( string[] args )
{
var numbers = new List<int>();
while(whatever)
{
var input = Console.ReadLine();
var lines = input.Split(
new char[] { ' ' },
StringSplitOptions.RemoveEmptyEntries
);
foreach( var line in lines )
{
int result;
if( !int.TryParse( line, out result ) )
{
// error handling
continue;
}
numbers.Add( result );
}
}
}
You can use the Split method, to break the line into numbers.
while (true)
{
var s = Console.ReadLine();
if (s == null) break;
foreach (var token in s.Split(' '))
{
int myNumber = int.Parse(token);
// ... do something ....
}
}
You problem is about converting strings into integers, as Console.Readline always returns a string.
There are many ways to parse multiple ints, but you will basically need to split the string using some method. I don't know of a Scanner in C# (but I guess you should seach for some kind of tokenizer to find it, since this would be the standard name.
Writing one is not that hard, especially if you only expect integers to be separated by spaces. Implementing it in a method could be something like
// Optional seperators
public IEnumerable<int> ParseInts(string integers, params char[] separators)
{
foreach (var intString in integers.Split(separators))
{
yield return int.Parse(intString);
}
}
public IEnumerable<int> ParseInts(string integers)
{
return ParseInts(integers, ' ');
}
Use this
string[] lines = File.ReadAllLines("Path to your file");
foreach (string line in lines)
{
if (line.Trim() == "")
{
continue;
}
string[] numbers = line.Trim().Split(' ');
foreach (var item in numbers)
{
int number;
if (int.TryParse(item, out number))
{
// you have your number here;
}
}
}
I've been doing this on HackerRank a lot, here's a helper method I use for reading an array of integers:
static int [] StringToIntArray(string s) {
string [] parts = s.Split(' ');
int [] arr = new int[parts.Length];
for (int i = 0; i < arr.Length; i++) {
arr[i] = Convert.ToInt32(parts[i]);
}
return arr;
}
Here's a sample reading two numbers on one line, then two lines with those many numbers into arrays:
string [] parts = Console.ReadLine().Split(' ');
int n = Convert.ToInt32(parts[0]);
int m = Convert.ToInt32(parts[1]);
int [] a = StringToIntArray(Console.ReadLine());
int [] b = StringToIntArray(Console.ReadLine());
Sample input:
3 5
40 50 60
10 20 30 100 7500
i have a String in HTML (1-3 of 3 Trip) how do i get the number 3(before trip) and convert it to int.I want to use it as a count
Found this code
public static string GetNumberFromStr(string str)
{
str = str.Trim();
Match m = Regex.Match(str, #"^[\+\-]?\d*\.?[Ee]?[\+\-]?\d*$");
return (m.Value);
}
But it can only get 1 number
Regex is unnecessary overhead in your case. try this:
int ExtractNumber(string input)
{
int number = Convert.ToInt32(input.Split(' ')[2]);
return number;
}
Other useful methods for Googlers:
// throws exception if it fails
int i = int.Parse(someString);
// returns false if it fails, returns true and changes `i` if it succeeds
bool b = int.TryParse(someString, out i);
// this one is able to convert any numeric Unicode character to a double. Returns -1 if it fails
double two = char.GetNumericValue('٢')
Forget Regex. This code splits the string using a space as a delimiter and gets the number in the index 2 position.
string trip = "1-3 of 3 trip";
string[] array = trip.Split(' ');
int theNumberYouWant = int.Parse(array[2]);
Try this:
public static int GetNumberFromStr(string str)
{
str = str.Trim();
Match m = Regex.Match(str, #"^.*of\s(?<TripCount>\d+)");
return m.Groups["TripCount"].Length > 0 ? int.Parse(m.Groups["TripCount"].Value) : 0;
}
Another way to do it:
public static int[] GetNumbersFromString(string str)
{
List<int> result = new List<int>();
string[] numbers = Regex.Split(input, #"\D+");
int i;
foreach (string value in numbers)
{
if (int.TryParse(value, out i))
{
result.Add(i);
}
}
return result.ToArray();
}
Example of how to use:
const string input = "There are 4 numbers in this string: 40, 30, and 10.";
int[] numbers = MyHelperClass.GetNumbersFromString();
for(i = 0; i < numbers.length; i++)
{
Console.WriteLine("Number {0}: {1}", i + 1, number[i]);
}
Output:
Number: 4
Number: 40
Number: 30
Number: 10
Thanks to: http://www.dotnetperls.com/regex-split-numbers
If I'm reading your question properly, you'll get a string that is a single digit number followed by ' Trip' and you want to get the numeric value out?
public static int GetTripNumber(string tripEntry)
{
return int.Parse(tripEntry.ToCharArray()[0]);
}
Not really sure if you mean that you always have "(x-y of y Trip)" as a part of the string you parse...if you look at the pattern it only catches the "x-y" part thought with the acceptance of .Ee+- as seperators. If you want to catch the "y Trip" part you will have to look at another regex instead.
You could do a simple, if you change the return type to int instead of string:
Match m = Regex.Match(str, #"(?<maxTrips>\d+)\sTrip");
return m.Groups["maxTrips"].Lenght > 0 ? Convert.ToInt32(m.Groups["maxTrips"].Value) : 0;
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.