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();
}
}
}
Related
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 ...
I am trying to get input from user 5 times and add those values to marks array;
Then, it will calculate the average and print positive or negative accordingly. However, I can not take input from the user it just prints "Enter 5 elements". After getting input from user how can I add them to marks array? Any tips would be helpful.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
double average =0;
int [] marks = new int[] { };
for (int a = 0; a < 5; a++){
Console.WriteLine("Enter 5 elements:");
string line = Console.ReadLine();
Console.WriteLine(line);
}
for (int i = 0; i < marks.Length; i++){
average = marks.Average();
}
if(average>0){
Console.WriteLine("Positive");
}else{
Console.WriteLine("Negative");
}
}
}
I would use a while loop combined with int.TryParse to check if the user input is a number. Also it doesn't make any sense to put average = marks.Average(); inside a for loop, because LINQ Average calculates the average of a collection (in your case the marks array).
static void Main()
{
int[] marks = new int[5];
int a = 0;
Console.WriteLine("Enter 5 elements:");
while (a < 5)
{
if (int.TryParse(Console.ReadLine(), out marks[a]))
a++;
else
Console.WriteLine("You didn't enter a number! Please enter again!");
}
double average = marks.Average();
if (average > 0)
Console.WriteLine("Positive");
else
Console.WriteLine("Negative");
}
DEMO HERE
Edited my answer to illustrate solving your problem without a for loop.
class Program
{
const int numberOfMarks = 5;
static void Main()
{
List<int> marks = new List<int>();
Enumerable.Range(1, numberOfMarks)
.ForEach((i) => {
Console.Write($"Enter element {i}:");
marks.Add(int.TryParse(Console.ReadLine(), out var valueRead) ? valueRead : 0);
Console.WriteLine($" {valueRead}");
});
Console.WriteLine(marks.Average() >= 0 ? "Positive" : "Negative");
}
}
This will help you, just copy and paste it.
There are some explanation with comments.
class Program
{
static void Main()
{
const int numberOfMarks = 5;
int[] marks = new int[numberOfMarks];
Console.WriteLine("Enter 5 elements:");
for (int a = 0; a < numberOfMarks; a++)
{
// If entered character not a number, give a chance to try again till number not entered
while(!int.TryParse(Console.ReadLine(), out marks[a]))
{
Console.WriteLine("Entered not a character");
}
Console.WriteLine("You entered : " + marks[a]);
}
// Have to call Average only once.
var avg = marks.Average();
Console.WriteLine(avg > 0 ? "Positive average" : "Negative average");
Console.ReadLine();
}
}
Follow Stackoverflow Answer
since integer array is being used, and as input from the console is a string value, you need to convert it using Parse() Method. For e.g.
string words = "83";
int number = int.Parse(words);
Edit: using string variable in parsing.
I have code here and based on user input, I'd like to change the line of choice I will have selected. However, I can only currently temporarily change the line of text and when I write out the file again, the text had not overwritten permanently.
Here's my code:
public struct classMates
{
public string first;
public string last;
public int ID;
}
static classMates[] readClassMates(classMates[] classMateInfo)
{
StreamReader sr = new StreamReader(#"C:\class.txt");
int count = 0;
while (!sr.EndOfStream)
{
classMateInfo[count].first = sr.ReadLine();
classMateInfo[count].last = sr.ReadLine();
string idTemp = sr.ReadLine();
classMateInfo[count].ID = Convert.ToInt32(idTemp);
count++;
}
sr.Close();
return classMateInfo;
}
static void editClassMates(classMates[] classMateInfo)
{
Console.Write("Who's number would you like to change? ");
string classMateInput = Console.ReadLine();
for (int i = 0; i < classMateInfo.Length; i++)
{
if (classMateInfo[i].first.Equals(classMateInput))
{
Console.Write("Enter new number: ");
string temp = Console.ReadLine();
int classMateNumber = Convert.ToInt32(temp);
classMateInfo[i].ID = classMateNumber;
Console.WriteLine("You have successfully changed {0}'s number to {1}.", classMateInfo[i].first,classMateInfo[i].ID.ToString());
}
}
}
static void Main()
{
classMates[] classMateInfo = new classMates[43];
listClassMates(classMateInfo);
editClassMates(classMateInfo);
listClassMates(classMateInfo);
}
I know I am meant to use File.WriteAllText(), but I don't know how to utilize this snippet into my code.
Maybe you're expecting an easy answer but you actually require custom code that you need to think up yourself.
If you're into LINQ and really want to use the File.WriteAllText() method you can use this oneliner i wrote for you, which I haven't tested:
File.WriteAllText(#"C:\class.txt", string.Join(Environment.NewLine, (from cm in classMateInfo select string.Format("{1}{0}{2}{0}{3}", Environment.NewLine, cm.first, cm.last, cm.ID)).ToArray()));
Which creates a string array from your classMateInfo, concatenates the array using a newline as separator and write the entire string to the specified file.
I donĀ“t see you writing anything to a file.
Console.Write("Enter new number: ");
string temp = Console.ReadLine();
int classMateNumber = Convert.ToInt32(temp);
classMateInfo[i].ID = classMateNumber;
Console.WriteLine("You have successfully changed {0}'s number to {1}.", classMateInfo[i].first,classMateInfo[i].ID.ToString());
I should expect that you did something like:
rs.Writeline('foo');
But perhaps you need a streamwriter for that.
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));
}
}
}
Morning all,
I have a simple question that I could do with some help with.
I need to create a list of strings that will start with A and finish at some other point e.g BBB, but I am not sure the best and fastest way of doing it.
Thanks in advance.
Ok as requested more information.
I need to create a simple way of creating a list of bays for a warehouse. This wareshouse can have a variable number of Aisles in it, a variable number of rows in each aisle and a variable number of bins for the row. So when the user comes to setup their particular warehouse they can specify the start letter of the Aisle and the end letter of the Aisle.
As you can now see the hardcoded list from A to ... isn't going to work.
No error checking (start number could be greater than end number in which case you would get an infinite loop) but the code works fine.
Hope you at least understand it before submitting it!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace testList
{
class Program
{
static void Main(string[] args)
{
Console.Write((int)'A');
Console.Write((int)'Z');
Console.WriteLine("Whats the starting string?");
string start = Console.ReadLine().ToUpper();
Console.WriteLine("Whats the end string?");
string end = Console.ReadLine().ToUpper();
List<string> retVal = new List<string>();
retVal.Add(start);
string currentString = start;
while (currentString != end)
{
currentString = IncrementString(currentString);
Console.WriteLine(currentString);
retVal.Add(currentString);
}
retVal.Add(end);
Console.WriteLine("Done");
Console.ReadKey();
}
private static string IncrementString(string currentString)
{
StringBuilder retVal = new StringBuilder(currentString);
char endChar= currentString[currentString.Length - 1];
for (int x = (currentString.Length - 1); x >= 0; x--)
{
char c = currentString[x];
if (TryIncrementChar(ref c))
{
retVal[x] = c;
break;
}
else
{
retVal[x] = 'A';
if (x == 0)
{
retVal.Insert(0,'A');
}
}
}
return retVal.ToString();
}
private static bool TryIncrementChar(ref char currChar)
{
if (currChar != 'Z')
{
currChar++;
return true;
}
return false;
}
}
}