I'm designing a program to save food recipes. The problem is when I save the ingredients of a new recipe it deletes the ingredients of the old recipe. I want both of them to be saved. Here's the code I use:
Console.WriteLine("Enter the path where your files will be saved: ");
string fileName = Console.ReadLine();
Console.WriteLine("Please enter the main ingrediant for your recipe: ");
string Main = Console.ReadLine();
Console.WriteLine("Please enter how many ingrediants in your recipe: ");
int Ingrediants = Convert.ToInt32(Console.ReadLine());
string[] a = new string[Ingrediants];
Recpies recipe1 = new Recpies(Main, Ingrediants);
recipe1.Ingrediants = new List<string[]>();
recipe1.TheMainIngrediant = Main;
Console.WriteLine("Please enter your ingrediants: ");
for (int i = 0; i < Ingrediants; i++)
{
a[i] = Console.ReadLine();
}
using (var file = System.IO.File.OpenText(fileName))
{
string line;
while ((line = file.ReadLine()?.Trim()) != null)
{
// skip empty lines
if (line == string.Empty)
{
recipe1.Ingrediants.Add(a);
recipe1.Saving(fileName, Ingrediants, a);
}
else
{
continue;
}
}
}
One possible way to achieve what you want is to use a combination between StreamWriter and File.AppendText, this is not going to overwrite the text you already save on that file instead of that is going to append the info at the end of the file (this example might be helpful: Append Text). Hope this helps! 👍
Just add true as second parameter
TextWriter tsw = new StreamWriter(fileName, true);
How do I check if user input matches a number in an array?
I've learned to compare user input or search using a string array, however doing the same with an int array is not working for me.
zipCode[i] = 0;
int userZip = 0;
do
{
Console.WriteLine( "enter a 5 digit zip code to see if it is supported in our area." );
Console.WriteLine( );
Console.WriteLine( "Enter a 0 to exit the program" );
userZip = 0;
if ( userZip == zipCode[i] )
{
found = true;
if ( found )
{
Console.WriteLine( "We support zip code {0}", userZip ); ;
}
else
{
Console.WriteLine( "We do not support", userZip );
}
}
} while ( userZip != 0 );
Console.ReadLine( );
How do I check if user input matches a number in an array?
using System;
using System.Collections.Generic;
public class Program
{
static List<string> _zipCodes;
static Program()
{
_zipCodes = new List<string>() { "80205", "80225", "80210" };
}
static void Main(string[] args)
{
string userZip = string.Empty;
do
{
Console.WriteLine("enter a 5 digit zip code to see if it is supported in our area.");
Console.WriteLine();
Console.WriteLine("Enter a -1 to exit the program");
userZip = Console.ReadLine();
if (_zipCodes.Contains(userZip))//<---------------THAT WAY
{
Console.WriteLine("We support zip code {0}", userZip); ;
}
else
{
Console.WriteLine("We do not support zip code {0}", userZip);
}
} while (userZip != "-1");
}
}
How do I check if user input matches a number in an array?
I will answer this question, though I can't post an example using your sample code since it's incomplete and it's not exactly clear what it's supposed to do.
First, let's create a method that gets an integer from the user. This method will continually loop until the user enters a valid integer:
public static int GetIntFromUser(string prompt = null)
{
int input;
int row = Console.CursorTop;
int promptLength = prompt?.Length ?? 0;
do
{
Console.SetCursorPosition(0, row);
Console.Write(prompt + new string(' ', Console.WindowWidth - promptLength - 1));
Console.CursorLeft = promptLength;
} while (!int.TryParse(Console.ReadLine(), out input));
return input;
}
Now, we can use that method to get the zip code from the user:
int userZipCode = GetIntFromUser("Enter a 5 digit zip code to see if it's supported: ");
Now I'm assuming you have an array of zip codes that are supported. Perhaps something like:
private static int[] GetSeattleZipCodes()
{
return new []
{
98101, 98102, 98103, 98104, 98105, 98106, 98107, 98108, 98109, 98110,
98111, 98112, 98113, 98114, 98115, 98116, 98117, 98118, 98119, 98121,
98122, 98124, 98125, 98126, 98127, 98129, 98131, 98133, 98134, 98136,
98138, 98139, 98141, 98144, 98145, 98146, 98148, 98154, 98155, 98158,
98160, 98161, 98164, 98165, 98166, 98168, 98170, 98174, 98175, 98177,
98178, 98181, 98185, 98188, 98190, 98191, 98194, 98195, 98198, 98199
};
}
So, now we have an int user input, and an int[] of valid zip codes, so to see if the array of valid zip codes contains the user zip code, we can just use the Contains method:
int[] seattleZipCodes = GetSeattleZipCodes();
bool found = seattleZipCodes.Contains(userZipCode);
TheFastCat beat me, but:
using System;
using System.Collections.Generic;
namespace ConsoleApplication1
{
class Program
{
private static IEnumerable<string> zipCodes = new string[] { "90210", "94102", "98101", "80014" };
static void Main(string[] args)
{
Console.WriteLine("enter a 5 digit zip code to see if it is supported in our area, or '0' to exit");
do {
// Read next line
string userZip = Console.ReadLine().Trim();
// Exit program?
if (userZip == "0")
break;
// Validate input
if (userZip.Length != 5)
{
Console.WriteLine("ERROR: Zip code {0} is {1} characters; expected 5", userZip, userZip.Length);
continue;
}
int n;
bool isNumeric = int.TryParse(userZip, out n);
if (!isNumeric)
{
Console.WriteLine("ERROR: Zip code {0} must be numeric", userZip);
continue;
}
// Finally, see if our zip code matches a zip code in the list
bool found = zipCodes.Contains(userZip);
if (found)
{
Console.WriteLine("We support zip code {0}", userZip); ;
}
else
{
Console.WriteLine("We do not support " + userZip);
}
} while (true);
Console.WriteLine("Done: exiting program");
}
}
}
Note:
Initializing the list
Validating the input
Using IEnumerable.Contains() ... without necessarily messing with LINQ.
Use of "break" and "continue" to control the loop, without necessarily needing an extraneous variable.
An int array is Enumerable<int>, so you could just use Contains(): https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.contains?view=netframework-4.7.2
TheFastCat and Rufus L done great job.
I just want to add an example. Using 'var' datatypes makes things easy and durable as well in C#
This example demonstrates both 'int' and 'string' using var datatypes in both cases. Good luck haberjin.
static void Main(string[] args)
{
//var ZipCodes = new List<string>() { "04846", "40569", "76859","54896", "84623" }; // ZipCodes are stored as a string in a List
var ZipCodes = new List<int>() { 04846, 40569, 76859, 54896, 84623 }; // ZipCodes are stored as an int in a List
//var userZip = "";
var userZip = 0;
do
{
Console.WriteLine("Enter a 5 digit zip code to see if it is supported in our area.");
//userZip = Console.ReadLine(); // Enable to receive userZip as a string
userZip = int.Parse(Console.ReadLine()); // receive userZip as an int
if (ZipCodes.Contains(userZip))
{
Console.WriteLine("We support zip code {0}", userZip);
}
else
{
Console.WriteLine("We do not support", userZip);
}
//} while (userZip != "0");
} while (userZip != 0);
}
The code below is supposed to read a text file and count all ASCII characters in the file and add up the frequency. Then, it has to write the character, ASCII value and frequency to an output file. The code is below:
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()
{
Console.WriteLine("Enter the file path");
var InputFileName = Console.ReadLine();
Console.WriteLine("Enter the outputfile name");
var 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 (!al.Contains(data[i]))
{
al.Add(data[i] + "(" + (int)data[i] + ")" + f + " ");
}
else
{
k++;
}
//i added the below if statement but it did not fix the issue
foreach (var item in al)
{
streamWriter.WriteLine(item);
}
}
streamWriter.Close();
}
}
The code compiles and runs perfectly fine, but the output file is not correct. It is adding letters that have already been reviewed. I've added an image with the output file showing the incorrect output it is creating. --> enter image description here
How do I check if a character already exists in the array list? The way I am using is not working properly and I have been working on this for a few weeks now to no success. I have tried using the debugger but this issue will not show up there as the code still runs and compiles correctly.
An ArrayList is not well suited for this task, and in fact ArrayLists are not really used anymore. If someone is telling you that you have to do this with an ArrayList
A dictionary would be a much better container for this data. You can use the character as the key, and the count as the value.
Here's one way to do this:
var inputPath = #"c:\temp\temp.txt";
var outputPath = #"c:\temp\results.txt";
var data = new Dictionary<char, int>();
// For each character in the file, add it to the dictionary
// or increment the count if it already exists
foreach (var character in File.ReadAllText(inputPath))
{
if (data.ContainsKey(character)) data[character]++;
else data.Add(character, 1);
}
// Create our results summary
var results = data.ToList()
.Select(item => $"{item.Key} ({(int) item.Key}) {item.Value}");
// Write results to output file
File.WriteAllLines(outputPath, results);
If you have to use an ArrayList (which no one ever uses anymore, but you say have you to for some reason), it would only be useful for storing the results but not keeping track of the counts.
One way to use an ArrayList would be in combination with the Linq extension methods Distinct and Count (first to find all distinct characters, and next to get the count of each one):
foreach (var chr in data.Distinct())
{
al.Add($"{chr} ({(int) chr}) {data.Count(c => c == chr)}");
}
Your algorithm works, but you are duplicating the output as you are writing to the file inside the loop, that is why you are seeing duplicates in the result. If you move the code outside the loop, it should be ok.
foreach (var item in al)
{
streamWriter.WriteLine(item);
}
I would suggest that your algorithm while correct will behave poorly for performance, you are doing too many unnecessary comparisons, perhaps you should read/check more about using dictionaries to store the results.
I'm trying to load the data from a comma delimited .txt file and put the information in 2 parallel arrays. The .txt file holds two columns of data, StudentName & StudentGrades.
Its looks similar to this...
Sally,67
Frank,32
John, 98
I'm trying to use the split method to read the comma delimited file, however I've tried many different ways to get this to work with no luck. The error that I am getting is "Cannot implicitly convert type string[] to string"
If I put the .txt data each on seperate lines and remove the split method from the code it works fine. However I need the file to be comma delimited.
public static void LoadArray()
{
StreamReader studentInfoStreamReader = new StreamReader("LittleRecord2.txt");
for (counter = 0; counter < 21; counter++)
{
if (studentInfoStreamReader.Peek() != -1) // CHECK TO SEE IF END OF FILE
{
studentName[counter] = (studentInfoStreamReader.ReadLine().Split(',')); // CODE WITH ERROR
studentGrade[counter] = Convert.ToInt32(studentInfoStreamReader.ReadLine());
}
}
studentInfoStreamReader.Close();
}
public static void OptionOne()
{
LoadArray();
Console.WriteLine("Student Name".ToString().PadRight(20) + ("Student Grade".ToString().PadRight(5)));
Console.WriteLine();
for (int c = 0; c < counter; c++)
{
Console.WriteLine("{0} {1}", studentName[c].PadRight(20), studentGrade[c].ToString().PadRight(5));
}
}
The Split method returns an array. In your case when you split using the comma, it will result in an array with 2 items. The first item at index 0 is the name and the 2nd item at index 1 is the grade:
var splitParts = (studentInfoStreamReader.ReadLine().Split(','));
studentName[counter] = splitParts[0];
studentGrade[counter] = Convert.ToInt32(splitParts[1]);
Instead of parallel arrays, it would be much more efficient to use a class. Also unless your file has millions of entries reading the whole file into memory would probably be much quicker:
class Student
{
public string name = "";
public int grade = 0;
public Student()
{
}
}
List<Student> GetStudents(string fileName)
{
return (from string line in System.IO.File.ReadAllLines(fileName)
let data = line.Split(",".ToArray())
select new Student { name = data[0], grade = int.Parse(data[1]) }).ToList();
}
This is because string.Split() returns an array and you're assigning it to a scalar value. Store the split result in a new array variable and then assign its elements separately:
public static void LoadArray()
{
StreamReader studentInfoStreamReader = new StreamReader("LittleRecord2.txt");
for (counter = 0; counter < 21; counter++)
{
if (studentInfoStreamReader.Peek() != -1) // CHECK TO SEE IF END OF FILE
{
var splitLine = studentInfoStreamReader.ReadLine().Split(',');
studentName[counter] = splitLine[0];
studentGrade[counter] = splitLine[1];
}
}
studentInfoStreamReader.Close();
}
string[] x = studentInfoStreamReader.ReadLine().Split(',');
studentName[counter] = x[0];
studentGrade[counter] = x[1];
I wrote a program, what is compute the difference of two string or compute a hamming distance.
I run in debug mode. And I saw, the at the string first the first element of string is missing. But the string second is good!
When I tested the first's length and second's length is equal.
Forexample:
I typed this: 00011
And in debug mode it's value only: 0011
. Or I typed this: "this", in debug the real value is only "his"
Somebody can explain me, why missing the first element of string?
The code:
while (Console.Read() != 'X')
{
string first = Console.ReadLine();
string second = Console.ReadLine();
int distance = 0;
for (int i = 0; i < first.Length; i++)
{
if (first[i]!= second[i])
{
++distance;
}
}
Console.WriteLine("Hamming distance is {0}.", distance);
}
I tried modify the iteration, forexample the loop was ++i, or the first[i-1] but these aren't solve my problem.
Console.Read() reads the first character from the buffer. This character will not be included in the ReadLine().
I would personally find a better way to end your program such as if first=="quit" or by some other syntaxic means.
You consume the first char with Console.Read() so it will not appear in first:
string first = Console.ReadLine();
while ((first != null) && (first[0] != 'X'))
{
string second = Console.ReadLine();
int distance = 0;
for (int i = 0; i < first.Length; i++)
{
if (first[i]!= second[i])
{
++distance;
}
}
Console.WriteLine("Hamming distance is {0}.", distance);
first = Console.ReadLine();
}
I have the same problem in vb.net and found out that it was causing by "console.readkey()". console should only read one at time.See you have multiple read function at same time.
like Readkey() at main() and readline() on Background.thread...
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace_File_Handling
{
class Program
{
static void Main(string[] args)
{
string path = #"E:\File.txt";
StreamReader r1 = new StreamReader(path);
string m = r1.ReadToEnd();
Console.WriteLine(m);
Console.ReadKey();
r1.Close();
StreamWriter wr = File.AppendText(path);
string na = Convert.ToString(Console.ReadLine());
wr.WriteLine(na);
wr.Close();
Console.WriteLine(na);
Console.ReadKey();
StreamReader rd = new StreamReader(path);
string val = rd.ReadToEnd();
Console.WriteLine(val);
rd.Close();
Console.ReadKey();
}
}
}