This question already has answers here:
Get property value from string using reflection
(24 answers)
string to variable name
(4 answers)
Closed 6 months ago.
I would be thankful if someone help me to resolve some task.
I need to create several variables using cycle "for".
I ask users how many numbers will they input, and declare it like variable "countVariables".
Next step, using cycle "for" I want to create new variables using counter cycle`s "for".
For example, name of created var must be like "num1", "num2", "num3" etc. I try do it using a code below.
I understand, that it isn't good solution, but I need to resolve task just using this way.
Console.WriteLine("Input count of numbers: ");
ushort.TryParse(Console.ReadLine(), out ushort countVariables);
for (int i = 1; i <= countVariables; i++)
{
string tmp = "num" + i;
int tmp.name = Console.ReadLine();
}
You can't do it using variables as you've mentioned but you can use Arrays instead. After reading number of times to repeat, you can create an array based on that then access values by index:
Console.WriteLine("Input count of numbers: ");
ushort.TryParse(Console.ReadLine(), out ushort countVariables);
var data = new string[countVariables];
for (int i = 1; i <= countVariables; i++)
{
string tmp = "num" + i;
data[i] = Console.ReadLine();
}
Later after the for loop you can access your values using data[0], data[1]... or use another for loop for looping over the values.
You can use a Dictionary for storing the data:
var data = new Dictionary<int, string>();
Console.WriteLine("Input count of numbers: ");
ushort.TryParse(Console.ReadLine(), out ushort countVariables);
for (int i = 1; i <= countVariables; i++)
{
var val = Console.ReadLine();
data.Add(i, val);
}
Write out number on index '4':
Console.WriteLine(data[4]);
Related
Supposing I have some variables with names : daywinner1 , daywinner2 , daywinner3...
How can I loop over these variables by increasing their incremental components ???
I've tried but I can't achieve it
My code :
string[][] olympia =
{
new string[]{"a","b","c" },
new string[]{"d","e"},
new string[]{"f","g","h","j","k"}
};
int daywinner1 = int.Parse(Console.ReadLine());
int daywinner2 = int.Parse(Console.ReadLine());
int daywinner3 = int.Parse(Console.ReadLine());
for (int i = 0; i < olympia.Length; i++)
{
Console.WriteLine(olympia[][]);
}
It is not possible to iterate over variable names in this way, as each variable is a discrete, separate box.
There is no relationship between "daywinner1", "daywinner2" and "daywinner3" in the code.
You could have named them "distance", "height" and "width", or "red, blue, green". There is no way for the compiler to know what their relationship with each other is, or what order they should be in.
However, you could instead create an array, where each element contains the value you want in an explicit order.
For example:
int[] daywinners = new int[3];
daywinners[0] = int.Parse(Console.ReadLine());
daywinners[1] = int.Parse(Console.ReadLine());
daywinners[2] = int.Parse(Console.ReadLine());
You can then iterate over the array of daywinners like so:
foreach (var daywinner in daywinners) {
}
I recommend learning more about data structures.
This question already has answers here:
Add new item in existing array in c#.net
(20 answers)
Closed 3 years ago.
I am trying to write a program that could catch user input of string type. Every time there is a space within this string, the program needs to get that part of the string and try to parse it to a decimal. The entries might be numbers that might be separated by a comma rather than just plain integers, that is why I would be using decimals instead of integers.
This is what I tried so far:
static void Main(string[] args)
{
Console.WriteLine("C# Exercise!" + Environment.NewLine);
Console.WriteLine("Please enter two numbers seperated by space to start calculating: ");
string[] input = Console.ReadLine().Split(' ');
//Currently allows for more than one value... I am not necessarily looking for a solution to this problem however.
Console.WriteLine(Environment.NewLine + "Result: ");
//Create the collection of decimals:
decimal[] numbers = { };
numbers[0] = 1.0m;//<-- Results in a System.IndexOutOfRangeException
for (int i = 0; i < input.Length; i++)
{
Console.WriteLine(input[i]);//<-- This value needs to be converted to a decimal and be added to a collection of decimals
}
/*decimal numberOne = ?? //<-- First decimal in the collection of decimals
decimal numberTwo = ?? //<-- Second decimal in the collection of decimals
Console.WriteLine(SumTrippler.Calculate(numberOne, numberTwo));*/
Console.WriteLine(SumTrippler.Calculate(decimal.Parse("0.5"), (decimal)0.5));//<-- Irrelevant method
Console.ReadKey();
}
How could I get two decimals as user input from the user and process this data by passing it to the method at the bottom of my program?
Edit: Closing this question because you are trying to relate a question that adds a string to a list is not a solid reason. I am not trying to add a string to a list.
You can use Array.ConvertAll() to convert string into decimal
var numbers = Array.ConvertAll(Console.ReadLine().Split(' '), decimal.Parse);
//Now you can iterate through decimal array
for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine(numbers[i]);
}
Your code will look like,
using System;
using System.Linq;
public static void Main(string[] args)
{
Console.WriteLine("C# Exercise!");
Console.WriteLine("Please enter two numbers seperated by space to start calculating: ");
var numbers = Array.ConvertAll(Console.ReadLine().Split(' '), decimal.Parse);
Console.WriteLine("Result: ");
for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine(numbers[i]);
}
decimal numberOne = numbers.FirstOrDefault();
decimal numberTwo = numbers.LastOrDefault(); //Your second element will be last element in array
Console.WriteLine(SumTrippler.Calculate(numberOne, numberTwo));
Console.ReadKey();
}
You have to initialize the array with the required number of fields (which can't be changed afterwards)
decimal[] numbers = new decimal[input.Length];
numbers[0] = 1.0m; // no more System.IndexOutOfRangeException
I'm trying to perform the job that an array is supposed to do, but without actually using one. I was wondering if this was possible, and if it is, how?
I have to initialize different variables, for example:
int value1 = 0;
int value2 = 0;
int value3 = 0;
int valueN = 0;
I want to receive a value from the user that determinate what is the for loop going to last.
Example: User --> 4
Then I can declare 4 variables and work with them.
for (i = 1; i <= 4; i++) {
Console.Write("Insert a number: ");
int value(i) = int.Parse(Console.ReadLine());
}
I expect to have 4 variables called equally, but with the only one difference that each one has a different number added at the end of the name.
// value1 = 0;
// value2 = 0;
// value3 = 0;
// valueN = 0;
You cannot create dynamically named variables in C# (and I am with those who are wondering why you want to do that). If you don't want to use an array, consider a Dictionary -- it would perform better than an array in some circumstances.
Dictionary<string, int> values = new Dictionary<string, int>();
for (int i = 1; i <= 4; i++)
{
values.Add("value" + i, 0);
}
value["value1"]; //retrieve from dictionary
I was asked to solve a problem in C# to get the sum of 'n' user inputs from console, which is separated by space, in a single line.
int n = Convert.ToInt32(Console.ReadLine());
int[] arr = new int[n];
int sum = 0;
for(int i = 0; i < n; i++) {
arr[i] = Convert.ToInt32(Console.ReadLine());
sum += arr[i];
}
Console.WriteLine("{0}",sum);
How can I modify this code to get the expected output from the space separated input?
Also the values need to be stored in array.
Input:
5
1 2 3 4 5
Output:
15
int result = Console.ReadLine().Split().Select(int.Parse).Sum();
You'll of course have to handle any bad user input as needed.
Per your added requirements:
int[] items = Console.ReadLine().Split().Select(int.Parse).ToArray();
int sum = items.Sum();
You could do something like this:
int result = input.Split(' ').Take(n).Select(int.Parse).Sum();
But it seems to me that you could avoid asking the user for the count, and just add together all the lines that they typed in:
string input = Console.ReadLine();
int result = input.Split(' ').Select(int.Parse).Sum();
Console.WriteLine(result);
(Note that this code does no error checking.)
EDIT: It seems that you want to have an array of ints. In that case, you can do it like this (again, with no error checking):
using System;
using System.Linq;
namespace Demo
{
internal class Program
{
private static void Main()
{
int n = int.Parse(Console.ReadLine());
int[] arr = Console.ReadLine().Split(' ').Take(n).Select(int.Parse).ToArray();
int sum = arr.Sum();
Console.WriteLine("{0}", sum);
}
}
}
You need to use the split function in C#. When you read the line, you get the whole line. This means you're attempting to say "sum = 0 plus Convert.ToInt32('5 1 2 3 4 5')" which doesn't work.
You need an array of integers equal to
Console.ReadLine().Split(" ");
String.Split function:
https://msdn.microsoft.com/en-us/library/b873y76a.aspx
using arr[i] = Convert.ToInt32(Console.ReadLine()) inside the loop will cause the program to expect an input on a different line and not on a single line.
What you can do is to take the input as a string and then split based on space, which produces an array of the inputed values. You can then sum them
Considering the fact that Naveen seems a student, I think some more code can explain better and let him learn some more from this exercise:
I've made a sample that gets some numbers separated by space or an enter and when the user enters a T calculates the sum in a traditional way using a loop and using Linq. I'm sure there are plenty of better ways to do the same, but maybe something a little bit more structured can be better to begin understanding C#.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SumTheNumbers
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Insert the numbers separated by a space or [Enter]> key, when finished write T and press [Enter] and you will have the result");
List<int> values = new List<int>();
while (true)
{
string inputData = Console.ReadLine();
if (inputData.ToUpper().StartsWith("T")) break;
string[] svals = inputData.Split(' ');
for (int i = 0; i < svals.Length; i++)
{
int x = 0;
int.TryParse(svals[i], out x);
if (x != 0) values.Add(x);
}
}
//Traditional mode
int total = 0;
for (int i = 0; i < values.Count; i++)
{
total = total + values[i];
}
//Linq mode
int totalLinq = values.Sum();
Console.WriteLine("The sum is");
Console.Write("Total: ");
Console.WriteLine(total.ToString());
Console.Write("Total linq: ");
Console.WriteLine(totalLinq.ToString());
Console.WriteLine("Press a key to end...");
Console.ReadKey();
}
}
}
So I'm trying to loop values into a two-dimensional array using foreach. I know the code should look something like this.
int calc = 0;
int[,] userfields = new int[3,3];
foreach (int userinput in userfields)
{
Console.Write("Number {0}: ", calc);
calc++;
userfields[] = Convert.ToInt32(Console.ReadLine());
}
This is as far as I can get. I tried using
userfields[calc,0] = Convert.ToInt32(Console.ReadLine());
but apparently that doesn't work with two-dimensional arrays. I'm relatively new with C# and I'm trying to learn, so I appreciate all of the answers.
Thanks in advance!
It is a two dimensional array as the name suggests it has two dimensions. So you need to specify two index when you want to assign a value. Like:
// set second column of first row to value 2
userfield[0,1] = 2;
In this case probably you want a for loop:
for(int i = 0; i < userfield.GetLength(0); i++)
{
for(int j = 0; j < userfield.GetLength(1); j++)
{
//TODO: validate the user input before parsing the integer
userfields[i,j] = Convert.ToInt32(Console.ReadLine());
}
}
For more information have a look at:
Multidimensional Arrays (C# Programming Guide)