How i count summary of numbers in a text file? - c#

I did this code, but it doesnt give summary. Still I can get numbers of each row, but not summary...
using System;
using System.IO;
namespace Progaram
{
class Count
{
static void Main()
{
using (StreamReader sr = new StreamReader("file.txt"))
{
string[] numbers = File.ReadAllLines("file.txt");
int summary = 0;
for (int i = 0; i < numbers.Length; i++)
{
summary += numbers[i];
//Console.WriteLine(numbers[i]);
}
Console.WriteLine(summary);
sr.ReadLine();
}
}
}
}

Your current solution will not compile.
You'll receive the following compilation error:
Cannot convert type 'string' to 'int'.
You'll want to convert the parsed string into an int.
Also, you're using a StreamReader, and reading a single line after reading in all lines. You don't need the StreamReader in this case.
using System;
using System.IO;
namespace Progaram
{
class Count
{
static void Main()
{
string[] numbers = File.ReadAllLines("file.txt");
int summary = 0;
for (int i = 0; i < numbers.Length; i++)
{
summary += Convert.ToInt32(numbers[i]);
}
Console.WriteLine(summary);
}
}
}

You can't add a string to an int.
You need to either convert the entire string array to an int array with
int[] intNumbers = Array.ConvertAll(numbers, int.Parse);
Then index this array instead
summary += intNumbers[i];
Or as Michael suggests, convert numbers[i] before adding
summary += int.Parse(numbers[i]);

Related

How to read C# . using StreamReader

I'm trying to read a string with StreamReader, so I don't know how to read it.
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
namespace
{
class Program
{
static void Main(string[] args)
{
string itemCostsInput = "25.34\n10.99\n250.22\n21.87\n50.24\n15";
string payerCountInput = "8\n";
string individualCostInput = "52.24\n";
double individualCost = RestaurantBillCalculator.CalculateIndividualCost(reader2, totalCost);
Debug.Assert(individualCost == 54.14);
uint payerCount = RestaurantBillCalculator.CalculatePayerCount(reader3, totalCost);
Debug.Assert(payerCount == 9);
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace as
{
public static class RestaurantBillCalculator
{
public static double CalculateTotalCost(StreamReader input)
{
// I want to read the input (not System.IO.StreamReader,
25.34
10.99
250.22
21.87
50.24
15
//below is what i tried..
int[] numbers = new int[6];
for (int i = 0; i < 5; i++)
{
numbers[int.Parse(input.ReadLine())]++;
}
for (int i = 0; i < 5; i++)
{
Console.WriteLine(numbers[i]);
}
return 0;
}
public static double CalculateIndividualCost(StreamReader input, double totalCost)
{
return 0;
}
public static uint CalculatePayerCount(StreamReader input, double totalCost)
{
return 0;
}
}
}
Even when I googled it, only file input/output came up with that phrase.
I want to get a simple string and read it.
int[] numbers = new int[6]; // The number at the index number
// take the given numbers
for (int i = 0; i < n; i++)
{
numbers[int. Parse(sr. ReadLine())]++;
}
I tried the above method, but it didn't work.
I just want to get the index and read the contents of itemCostsInput as it is. If I just execute Console.writeLine, String == System.IO.StreamReader
comes out I want to read and save the values of itemCostsInput respectively. I just want to do something like read.
I'm sorry I'm not good at English
I expected input Read
25.34
10.99
250.22
21.87
50.24
15
but console print System.IO.StreamReader
This lines are the ones causing (more) trouble I think:
for (int i = 0; i < 5; i++)
{
numbers[int.Parse(input.ReadLine())]++;
}
Should be
for (int i = 0; i < 5; i++)
{
numbers[i] = int.Parse(input.ReadLine());
}
But since you have a decimal input (in string format due to the streamreader), maybe numbers should be an array of decimals.
Also there are quite a few remarks about the use of StreamReader, since if the file doesn't have 5 or more lines, your program will also break. I let this here hoping will clarify something to you, though
Your code does not make sense in its current state.
Please read up on Streams.
Usually you'd get a stream from a file or from a network connection but not from a string.
You are confusing integer and double.
The double data type represents floating point numbers.
It seems to me that you just started programming and are missing out on most of the fundamentals.
First, convert your string input into a stream:
static System.IO.Stream GetStream(string input)
{
Stream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
writer.Write(input);
writer.Flush();
stream.Position = 0;
return stream;
}
Now you can convert your input to a stream like this:
// ... code ...
string itemCostsInput = "25.34\n10.99\n250.22\n21.87\n50.24\n15";
var dataStream = GetStream(itemCostsInput);
// ... code ...
Now you that you converted your string input into a stream you can start to parse your data and extract the numbers:
static List<double> GetDoubleFromStream(Stream stream)
{
if (stream == null) {
return new List<double>();
}
const char NEWLINE = '\n';
List<double> result = new List<double>();
using (var reader = new StreamReader(stream))
{
// Continue until end of stream has been reached.
while (reader.Peek() > -1)
{
string temp = string.Empty;
// Read while not end of stream and char is not new line.
while (reader.Peek() != NEWLINE && reader.Peek() > -1) {
temp += (char)reader.Read();
}
// Perform another read operation
// to skip the current new line character
// and continue reading.
reader.Read();
// Parse data to double if valid.
if (!(string.IsNullOrEmpty(temp)))
{
double d;
// Allow decimal points and ignore culture.
if (double.TryParse(
temp,
NumberStyles.AllowDecimalPoint,
CultureInfo.InvariantCulture,
out d))
{
result.Add(d);
}
}
}
}
return result;
}
This would be your intermediate result:
Now you can convert your input to a stream like this:
// ... code ...
string itemCostsInput = "25.34\n10.99\n250.22\n21.87\n50.24\n15";
var dataStream = GetStream(itemCostsInput);
var result = GetDoubleFromStream(dataStream);
// ... code ...

Check if string contains all required characters

I need to import a number of characters in a string format with a comma and check if a string is valid by containing all of them. The string must be in a format like that "AB2345CD" . This is the code I have for now but i dont know how to check if it is valid by containing all of the input characters and every digit between 0 and 9.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace License_Plates
{
class Program
{
static void Main(string[] args)
{
string input = Console.ReadLine();
var allowedCharacters = input.ToList();
int platesToValidate = int.Parse(Console.ReadLine());
List<string> plateNumbers = new List<string>();
for (int i = 0; i < platesToValidate; i++)
{
string plate = Console.ReadLine();
plateNumbers.Add(plate);
}
List<string> validNumbers = new List<string>();
foreach (var number in plateNumbers)
{
if (number.Contains(allowedCharacters.ToString()))
{
validNumbers.Add(number);
}
}
for (int i = 0; i < validNumbers.Count; i++)
{
Console.WriteLine(i);
}
}
}
}
Check if string contains all required characters
you could use the linq extension All:
var allowedstring = "A,B,C,D";
var allowednumber = "0,1,2,3,4,5,6,7,8,9";
var test1 = "ABC0";
var test2 = "AZ9";
var allowed = $"{allowedstring}{allowednumber}".Replace(",", "");
Console.WriteLine(test1.All(c => allowed.Contains(c))); //True
Console.WriteLine(test2.All(c => allowed.Contains(c))); //False

Character Counter using Array List

I need to design a program that reads in an ASCII text file and creates an output file that contains each unique ASCII character and the number of times it appears in the file. Each unique character in the file must be represented by a character frequency class instance. The character frequency objects must be stored in an array list. My code is below:
using System.IO;
using System;
using System.Collections;
namespace ASCII
{
class CharacterFrequency
{
char ch;
int frequency;
public char getCharacter()
{
return ch;
}
public void setCharacter(char ch)
{
this.ch = ch;
}
public int getfrequency()
{
return frequency;
}
public void setfrequency(int frequency)
{
this.frequency = frequency;
}
static void Main()
{
string OutputFileName;
string InputFileName;
Console.WriteLine("Enter the file path");
InputFileName = Console.ReadLine();
Console.WriteLine("Enter the outputfile name");
OutputFileName = Console.ReadLine();
StreamWriter streamWriter = new StreamWriter(OutputFileName);
string data = File.ReadAllText(InputFileName);
ArrayList al = new ArrayList();
//create two for loops to traverse through the arraylist and compare
for (int i = 0; i < data.Length; i++)
{
int k = 0;
int f = 0;
for (int j = 0; j < data.Length; j++)
{
if (data[i].Equals(data[j]))
{
f++;
if (i > j) { k++; }
}
}
al.Add(data[i] + "(" + (int)data[i] + ")" + f + " ");
foreach (var item in al)
{
streamWriter.WriteLine(item);
}
}
streamWriter.Close();
}
}
}
When I run the program, the program does not stop running and the output file keeps getting larger until it eventually runs out memory and I get an error stating that. I am not seeing where the error is or why the loop won't terminate. It should just count the characters but it seems to keep looping and repeating counting the characters. Any help?
Try this approach :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace yourNamespace
{
class Char_frrequency
{
Dictionary<Char, int> countMap = new Dictionary<char, int>();
public String getStringWithUniqueCharacters(String input)
{
List<Char> uniqueList = new List<Char>();
foreach (Char x in input)
{
if (countMap.ContainsKey(x))
{
countMap[x]++;
}
else
{
countMap.Add(x, 1);
}
if (!uniqueList.Contains(x))
{
uniqueList.Add(x);
}
}
Char[] uniqueArray = uniqueList.ToArray();
return new String(uniqueArray);
}
public int getFrequency(Char x)
{
return countMap[x];
}
}
}
This might not be the ideal solution. But you can use these methods

Why does an integer with value greater than loop limit gets passed to lambda

The code is to generate random numbers in 100 files numbered from 0..99.
What I couldn't get was why this code ended up creating a file called 100.txt and I even got an exception saying that 100.txt was being written by another process.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RandomNumbersFileGenerator
{
class Program
{
static Random Random = new Random();
static void Main(string[] args)
{
List<Task> tasks = new List<Task>();
for(int fileNumber = 0; fileNumber < 100; ++fileNumber)
{
tasks.Add(Task.Run(()=>GenerateFileWithRandomNumbers(Path.Combine($"c:\\FilesWithRandomNumbers\\{fileNumber}.txt"), 10000000)));
}
Task.WaitAll(tasks.ToArray());
}
static void GenerateFileWithRandomNumbers(string path, int numberOfNumbers)
{
List<string> listOfNumbers = new List<string>();
for(;numberOfNumbers > 0; --numberOfNumbers)
{
listOfNumbers.Add(Random.Next().ToString());
}
File.WriteAllLines(path, listOfNumbers);
}
}
}
It is related to closures and captured variables. Change
for(int fileNumber = 0; fileNumber < 100; ++fileNumber)
{
tasks.Add(Task.Run(()=>GenerateFileWithRandomNumbers(Path.Combine($"c:\\FilesWithRandomNumbers\\{fileNumber}.txt"), 10000000)));
}
To
for(int fileNumber = 0; fileNumber < 100; ++fileNumber)
{
int tmp = fileNumber;
tasks.Add(Task.Run(()=>GenerateFileWithRandomNumbers(Path.Combine($"c:\\FilesWithRandomNumbers\\{tmp}.txt"), 10000000)));
}
See also http://csharpindepth.com/articles/chapter5/closures.aspx

How do I read and separate the first portion of the array from the rest?

So I have a minor problem with my code and am almost certain that it should be an easy fix. So I have some data that I have in a file that reads:
25 150
60
63
61
70
72
68
66
68
70
The problem with this bit of data is that the first line: "25 150", are suppose to be saved as integers so that I can use them throughout the code. I have the problem solved without that line of numbers because the array can separate them as it normally does. How do I write the code so that it separates those two numbers and saves them as two different integers? This is the code I have so far:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace proj11LEA
{
class Program
{
const int SIZE = 50;
static void Main(string[] args)
{
int[] volts = new int[SIZE];
string environment = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal) + "\\";
Console.WriteLine("\nResistor Batch Test Analysis Program\n");
Console.WriteLine("Data file must be in your Documents folder.");
Console.WriteLine("Please enter the file name: ");
string input = Console.ReadLine();
string path = environment + input;
StreamReader data = new StreamReader(path);
string fromFile;
int count = 0;
int start = 1;
Console.WriteLine("\nRes#\tDissipation\tPassed");
do
{
fromFile = data.ReadLine();
if (fromFile != null)
{
string[] dataArray = fromFile.Split();
volts[count] = int.Parse(dataArray[0]);
count++;
}
} while (fromFile != null);
for (int i = 0; i < count; i++ )
{
int diss = (volts[i] * volts[i])/25;
if (diss >= 150)
{
string answer = ("yes");
Console.WriteLine("{0}\t{1:d2}\t\t{2}", start++, diss , answer);
}
else
{
string answer = ("no");
Console.WriteLine("{0}\t{1:d2}\t\t{2}", start++, diss, answer);
}
}
Console.ReadLine();
}
}
}
this will create a list of int from a text file of numbers like you have, then you can manipulate it how you need!
List<int> data = new List<int>();
using (StreamReader xReader = new StreamReader("TextFile1.txt"))
{
string line;
while (!xReader.EndOfStream)
{
line = xReader.ReadLine();
string[] input = line.Split(' ', '\r');// this splits the line on the space and newline
foreach (string item in input)
{
data.Add(Convert.ToInt32(item));
}
}
}

Categories