Console outputs System.int32[] when i try to convert string to int - c#

I am trying to output a few numbers that are in the same line as a string by converting them from string to int im using split and trying to convert for first time and the output is system.int32[]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
int Websites = int.Parse(Console.ReadLine());
int sectok = int.Parse(Console.ReadLine());
string[] webnamearray = new string[Websites];
int[] persums = new int[Websites];
int one = 0;
int two = 0;
string datainput = "";
for (int i = 0; i < Websites; i++)
{
datainput = Console.ReadLine();
string[] split = datainput.Split(' ');
webnamearray[i] = (split[0]);
one = int.Parse(split[1]);
two = int.Parse(split[2]);
persums[i] = one * two;
Console.WriteLine(persums);
}
for (int i = 0; i < Websites;i++)
{
Console.WriteLine(webnamearray[i]);
}
}
}
}

You wrote:
Console.WriteLine(persums);
which is an array of integers, that explains why you see that in your output.
I think instead your desired output is (which is your value that you just created):
Console.WriteLine(persums[i]);
and instead of if you want to place this information with the names change your last loop:
for (int i = 0; i < Websites;i++)
{
Console.WriteLine(webnamearray[i] + " " + persums[i]);
}

Related

Create a row array B, consisting of substrings of elements of array A

An array of strings A is given. Each element consists of the clients surname and name. Create a row array B, consisting of substrings of elements of array A and
containing only clients names.
My code doesn't work.
I enter Donna Paulson, Jhon Elliot, and i get Donna, Elliot.
It needs to be Paulson, Elliot, because only names are needed
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Clients
{
internal class Program
{
static void Main(string[] args)
{
int m = Convert.ToInt32(Console.ReadLine());
string[] A = new string[m];
string[] B = new string[m];
for (int i = 0; i < m; i++)
{
Console.Write($"A[{i}]= ");
A[i] = Console.ReadLine();
}
for (int i = 0; i < m; i++)
{
string[] text = A[i].Split(' ');
B[i] = text[i];
}
for (int i = 0; i < B.Length; i++)
{
Console.WriteLine(B[i]);
}
}
}
}

Multidimensional Array from a txt file

I need to create an 2D array from a text file.
my text file looks like this
Name1:Id1:Class1:Status1
Name2:Id2:Class2:Status2
and so on
I want my multidimensional array to make something like this
array = {{name1,id1,class1,status1},{name2,id2,class2,status2}}
I have seen other post related to it but non seems to be helping thats why posting again
I assume that all of the lines have the same format. We can simply iterate through the lines as below:
string[] lines = File.ReadAllLines(filename);
int len0 = lines.Length;
int len1 = lines[0].Split(':').Length;
string[,] array = new string[len0, len1];
for (int i= 0; i < len0; i++)
{
string line = lines[i];
string[] fields = line.Split(':');
if (fields.Length != len1)
continue; // to prevent error for the lines that do not meet the formatting
for(int j = 0; j < len1; j++)
{
array[i,j] = fields[j];
}
}
Going to a jagged array is pretty easy. Going from a jagged array to a 2D array just requires some assumptions: like that all rows have the same number of items and that you know how many rows and columns there are when you create the array.
string.Split will help you create the jagged array. And a straightforward loop will help you create the multi-dimensional array.
using System;
using System.Linq;
class Program {
static void Main(string[] args) {
string input = #"Name1:Id1:Class1:Status1
Name2:Id2:Class2:Status2";
var jagged = input
.Split(new string[] { Environment.NewLine }, StringSplitOptions.None)
.Select(s => s.Split(':').ToArray())
.ToArray();
var multi = new string[jagged.Length, jagged[0].Length];
for (int i = 0; i < jagged.Length; ++i) {
for (int j = 0; j < jagged[0].Length; ++j) {
multi[i, j] = jagged[i][j];
Console.WriteLine("[{0},{1}] = {2}", i, j, multi[i, j]);
}
}
}
}
It is better to use a List object like code below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.txt";
static void Main(string[] args)
{
List<List<string>> data = new List<List<string>>();
StreamReader reader = new StreamReader(FILENAME);
string line = "";
while ((line = reader.ReadLine()) != null)
{
List<string> lineArray = line.Split(new char[] { ':' }).ToList();
data.Add(lineArray);
}
reader.Close();
}
}
}

Error with program that opens file, reads data, and calculates the average

I was given an assignment in my programming class with a prompt that directly reads,
"In this exercise exam scores for a class of students is stored in a file. You are to write a program that successfully opens the file, reads in the exam scores, and outputs them on the console."
Every time I run my program an error occurs showing that,
"An unhandled exception of type 'System.IndexOutOfRangeException' occurred in GradeCalculator.exe"
The error appears on the code, "gradesArray[i] = gradesArray[gradeData];
i++;"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace GradeCalculator
{
class Program
{
static void Main(string[] args)
{
string folder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal) + "\\grades.txt";
int gradeData;
StreamReader grades = new StreamReader(folder);
int[] gradesArray = new int[50];
while (!grades.EndOfStream)
{
for (int i = 0; i != 50;)
{
gradeData = int.Parse(grades.ReadLine());
gradesArray[i] = gradesArray[gradeData];
i++;
}
}
Program calc = new Program();
for (int i = 0; i < 50; i++)
{
int average = calc.averageArr(gradesArray);
Console.WriteLine("{0}", average);
Console.ReadLine();
}
}
public int averageArr(int[] arr)
{
int avg = 0;
int numGrades = 0;
int sum = 0;
for (int i = 0; i < 50; i++)
{
do
{
sum += arr[i];
} while (arr[i] != 0);
}
avg = sum / numGrades;
return avg;
}
}
}
Any suggestions on how to fix this?
Data from file:
88
90
78
65
50
83
75
23
60
94
EDITED NEW CODE
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace GradeCalculator
{
class Program
{
static void Main(string[] args)
{
string folder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal) + "\\grades.txt";
int gradeData;
StreamReader grades = new StreamReader(folder);
int[] gradesArray = new int[50];
do
{
gradeData = int.Parse(grades.ReadLine());
for (int i = 0; i != gradesArray.Length;)
{
gradesArray[i] = gradeData;
i++;
}
}
while (!grades.EndOfStream);
Program calc = new Program();
int average = calc.averageArr(gradesArray);
Console.WriteLine("{0}", average);
Console.ReadLine();
}
public int averageArr(int[] arr)
{
int avg = 0;
int sum = 0;
for (int i = 0; i != arr.Length; )
{
sum += arr[i];
i++;
}
avg = sum / arr.Length;
return avg;
}
}
}
You have lot of redundant code, you simply could use Linq and get an array of int.
var intArray = File.ReadAllLines("filepath")
// Remove below line if you have only 1 number in each line, else specify delimiter and keep it.
.SelectMany(s=>s.Split(' '))
.Select(int.Parse);
Once you get the array, Array has function which returns Average
var average = intArray.Average();
Update:
Since you want to write function that calculates average, you could do this. Please note I modified few variable types to Decimal to avoid intdivision.
public decimal averageArr(int[] arr)
{
decimal avg = 0;
int numGrades = 0;
decimal sum = 0;
for (int i = 0; i < arr.Length; i++)
{
sum += arr[i];
}
avg = sum / arr.Length;
return avg;
}

Converting a 2d array along with its elements from string to int

As much as I tried to find a similar version in the question here, I couldn't find something.. so I am asking your help.
After reading some numbers from a textfile (now in string format), I split them in rows and columns and add them to a 2d-array (in string format as well). Now I want to convert everythinh in integers so that I can play with sorting the numbers out later.
Here is my code...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ArrayProgram
{
class Program
{
int number = 0;
int i = 0;
int k = 0;
string strnum;
public void onetohundredints()
{
StreamWriter writer = new StreamWriter("numberstored.txt");
for (i = 0; i < 10; i++)
{
for (k = 0; k < 10; k++)
{
number++;
Console.Write(number + " ");
strnum = number.ToString();
writer.Write(strnum + " ");
}
Console.WriteLine();
writer.WriteLine();
}
writer.Close();
}
public void readints()
{
StreamReader reader = new StreamReader("numberstored.txt");
string data = reader.ReadToEnd();
reader.Close();
string[,] dataarray = new string[10,10];
int[] numbers = new int[100];
string[] dataperlines = data.Split(new[] { '\r','\n' },StringSplitOptions.RemoveEmptyEntries);
for(int i=0; i<=dataperlines.Count()-1; i++)
{
string[] numbersperrow = dataperlines[i].Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
for (int j=0; j<=numbersperrow.Count()-1; j++)
{
dataarray[i, j] = numbersperrow[j];
}
}
}
public static void Main(string[] args)
{
Program prog = new Program();
prog.onetohundredints();
prog.readints();
Console.ReadKey();
}
}
}
After I insert the number into the 2d-array, how do I convert all of it in integers?
If you don't have a particular reason to have an array of strings, you can just save you data as int in the first place. Just change your inner for loop to do:
var parsed = int.TryParse(numbersperrow[j], out dataarray[i, j]);
if (!parsed)
{
// Error
}
While that should work, I would suggest to re-write your ReadData method to look similar to the sample below.
public int[,] ReadData(string filePath, int xDimension, int yDimension)
{
var results = new int[xDimension, yDimension];
var lines = File.ReadLines(filePath);
for (var i = 0; i < allLines.Count(); i++)
{
var values = lines[i].Split(new[] { ' ' },
StringSplitOptions.RemoveEmptyEntries);
for (var j = 0; j < values.Count(); j++)
{
var parsed = int.TryParse(values[j], out results[i, j]);
if (!parsed) { }
}
}
return results;
}
You're putting everything into a string array. That array can only hold strings, not numbers. If you want to make the 2d array hold numbers, define it as int[,] dataarray = new int[10,10]; Next, in the final loop, simply do dataarray[i, j] = Convert.ToInt32(numbersperrow[j]);
Edit: You can use int.TryParse(numbersperrow[j], out value) if you aren't sure that numbersperrow[j] will be a number. Value will return false if the conversion is not successful.
I am happy to say that both solutions work. I now have my numbers in my 2d array. But now I wish to play with them. Let's say that I want the numbers printed on the screen in reverse order.
Having this correct solution:
int numbers;
int[,] dataarray = new int[10,10];
string[] dataperlines = data.Split(new[] { '\r','\n' },StringSplitOptions.RemoveEmptyEntries);
for(int i=0; i<=dataperlines.Count()-1; i++)
{
string[] numbersperrow = dataperlines[i].Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
for (int j=0; j<=numbersperrow.Count()-1; j++)
{
numbers = int.Parse(numbersperrow[j]);
dataarray[i, j] = numbers;
Console.Write(numbers + " ");
}
Console.WriteLine();
}
I know that I have to make a double for loop. But how do I write a succesful syntax for the numbers to be printed properly?
I also tried this:
int[,] reversedarray = new int[10, 10];
reversedarray[i, j] = Array.Reverse(dataarray[i,j]);
but the dataarray[i,j] becomes red and the error "cannot convert from int to system.Array occurs... what am I missing?
I also tried this...
for (i = 10; i <= dataperlines.Count(); i--)
{
string[] numbersperrow = dataperlines[i].Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
for (j =10; j <= numbersperrow.Count(); j--)
{
numbers = int.Parse(numbersperrow[j]);
reversedarray[i, j] = numbers;
Console.Write(numbers + " ");
}
Console.WriteLine();
}
But I have an IndexOutOfRange exception coming from
string[] numbersperrow = dataperlines[i].Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
I understood that since I splitted the columns into rows too, it is unecessary to write it again, but I am stuck. I tried simplifying the code since I have my 2darray with its elements and I my tries were fallacious. Any more suggestions?

Exercise in C#,it doesn't work

this is the problem:You are given a sequence of positive integer numbers given as string of numbers separated by a space. Write a program, which calculates their sum. Example: "43 68 9 23 318" -> 461.
That's my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exercises2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Give some numbers");
int i = 0, j = 0;
string n = Console.ReadLine();
string[] numbers = n.Split(' ');
int[] array;
for (i = 0; i < numbers.Length; i++)
{
array = new int[int.Parse(numbers[i])];
int s = Sum(array);
Console.Write("the sum of your numbers is: {0} ", s);
}
}
static int Sum(int[] array)
{
int sum = 0;
for (int i = 0; i < array.Length; i++)
{
sum += array[i];
}
return sum;
}
}
}
I dont know why it doesn't work,is giving me that the sum is 0.
Thank you.
The problem is:
array = new int[int.Parse(numbers[i])];
You actually create array with the length is the given numbers[i]. the array values are all 0. So
int s = Sum(array);
s is always 0.
The correct code is simple:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Give some numbers");
int i = 0, j = 0;
string n = Console.ReadLine();
string[] numbers = n.Split(' ');
int s = 0;
for (i = 0; i < numbers.Length; i++)
{
s += int.Parse(numbers[i]);
}
Console.Write("the sum of your numbers is: {0} ", s);
Console.ReadLine();
}
}
You should only iterate on each element of your array of strings retrieved by .Split and sum.
working example .Net Fiddle:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class Program
{
public static void Main()
{
Console.WriteLine("Give some numbers");
string n = Console.ReadLine();
int sum = 0;
foreach(var i in n.Split(' ')){
sum += int.Parse(i);
}
Console.Write("the sum of your numbers is: {0} ", sum);
}
}
There is problem with the code where you getting the value of user given array in summation array as initialization of array.
array = new int[int.Parse(numbers[i])];
Here this is in loop array is initialized every time the value is getting. As per your input "43 68 9 23 318". Array will initialize by 43, then 68, then by 9 and so on. When array is initialized the values are by default 0 for int.
So Please refer this solution with proper null and integer check. Hope this will help you!.
static void Main(string[] args)
{
Console.WriteLine("Give some numbers");
int i = 0;
string n = Console.ReadLine();
string[] numbers = n.Split(' ');
if (numbers != null && numbers.Length > 0)
{
int[] array = new int[numbers.Length];
int s = 0;
for (i = 0; i < numbers.Length; i++)
{
// Check if numbers[i] values is integer then add to array for some
int number;
bool result = Int32.TryParse(numbers[i], out number);
if (result)
{
array[i] = number;
}
}
s = Sum(array);
Console.Write("The sum of your numbers is: {0} ", s);
}
Console.Read();
}

Categories