Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
using System;
namespace suma_cifrelor_unui_nr
{
class Program
{
static void Main(string[] args)
{
int n;
int suma = 0;
Console.Write("Introdu numarul ");
Console.Write("\n");
n = int.Parse(ConsoleInput.ReadToWhiteSpace(true));
while (n > 0)
{
suma = suma + n % 10;
n = n / 10;
}
Console.Write("Suma cifrelor este ==");
Console.Write(suma);
}
}
}
When I m trying to run this code the following error pops up :
"The name 'ConsoleInput' does not exist in the current context"
enter image description here
As expected ConsoleInput is a helper class so I did some google search,
And that's land me to convert code from c++ to c# and i found that words "with the 'ConsoleInput' helper class added by our converter", so try to check google before ask next time.
internal static class ConsoleInput
{
private static bool goodLastRead = false;
internal static bool LastReadWasGood
{
get
{
return goodLastRead;
}
}
internal static string ReadToWhiteSpace(bool skipLeadingWhiteSpace)
{
string input = "";
char nextChar;
while (char.IsWhiteSpace(nextChar = (char)System.Console.Read()))
{
//accumulate leading white space if skipLeadingWhiteSpace is false:
if (!skipLeadingWhiteSpace)
input += nextChar;
}
//the first non white space character:
input += nextChar;
//accumulate characters until white space is reached:
while (!char.IsWhiteSpace(nextChar = (char)System.Console.Read()))
{
input += nextChar;
}
goodLastRead = input.Length > 0;
return input;
}
internal static string ScanfRead(string unwantedSequence = null, int maxFieldLength = -1)
{
string input = "";
char nextChar;
if (unwantedSequence != null)
{
nextChar = '\0';
for (int charIndex = 0; charIndex < unwantedSequence.Length; charIndex++)
{
if (char.IsWhiteSpace(unwantedSequence[charIndex]))
{
//ignore all subsequent white space:
while (char.IsWhiteSpace(nextChar = (char)System.Console.Read()))
{
}
}
else
{
//ensure each character matches the expected character in the sequence:
nextChar = (char)System.Console.Read();
if (nextChar != unwantedSequence[charIndex])
return null;
}
}
input = nextChar.ToString();
if (maxFieldLength == 1)
return input;
}
while (!char.IsWhiteSpace(nextChar = (char)System.Console.Read()))
{
input += nextChar;
if (maxFieldLength == input.Length)
return input;
}
return input;
}
}
using System;
namespace suma_cifrelor_unui_nr
{
internal static class ConsoleInput
{
static void Main(string[] args)
{
int n;
int suma = 0;
Console.Write("Introdu numarul ");
Console.Write("\n");
n = int.Parse(ConsoleInput.ReadToWhiteSpace(true));
while (n > 0)
{
suma = suma + n % 10;
n = n / 10;
}
Console.Write("Suma cifrelor este ==");
Console.Write(suma);
}
private static ReadOnlySpan<char> ReadToWhiteSpace(bool v)
{
throw new NotImplementedException();
}
}
}
Related
I have this method:
public static string ReplaceVarReferences(string input,char open, char close)
{
string inner = "";
for (int i = 0; i < input.Length; i++)
{
if (input[i] == open)
{
i++;
string varInner = "";
while (input[i] != close)
{
varInner += input[i];
i++;
}
inner += GetVariable(varInner);
}
else
{
inner += input[i];
}
}
return inner;
}
and this memory allocation and retrieval methods:
public static Dictionary<string, string> memory = new Dictionary<string, string>();
public static string GetVariable(string key)
{
if (memory.ContainsKey(key))
{
return memory[key];
}
else
{
return key;
}
}
public static void SetVariable(string key, string value)
{
if (memory.ContainsKey(key))
{
memory[key] = value;
}
else
{
memory.Add(key, value);
}
}
I want to to return a string with the 'ReplaceVarReferences' method and return a string with multiple spaces like this:
this code is from my interpreter and not real code.
var a = hello world;
print(variable a = {a})
the 'ReplaceVarReferences' method should be able to return this with multiple spaces:
"variable a = hello world"
but instead, it returns:
"variable a = hello world"
how can I fix this?
Ok so I looked at the wrong place I have another method that had the problem:
public static string GetNested(string Open, string Close, List<string> t, ref int i)
{
string inner = "";
int nested = 0;
while (true)
{
if (i < t.Count - 1)
{
i++;
if (string.IsNullOrWhiteSpace(t[i]))
{
for (int x = 0; x < t[i].Length; x++)
{
inner += " ";
}
}
else if (t[i] == Close)
{
nested--;
if (nested > 0)
{
inner += t[i];
}
}
else if (t[i] == Open)
{
if (nested > 0)
{
inner += t[i];
}
nested++;
}
else
{
inner += t[i];
}
if (nested == 0)
{
break;
}
}
}
return inner;
}
i did not include:
if (string.IsNullOrWhiteSpace(t[i]))
{
for (int x = 0; x < t[i].Length; x++)
{
inner += " ";
}
}
and it resulted in the spaces being dumped when retrieving the nested string.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
How do I get out of this loop?
I wrote a program that checks to see if corresponding places in the numbers are the same total. The console output should be true or false. I wrote that, and then added the top part that interacts with the user, and now I get stuck in a loop. How do I get out of it?
using System;
namespace DeliverablePart1
{
class DeliverablePart1
{
static void Main(string[] args)
{
string gameAnswer;
bool repeat1 = true, repeat2 = true;
while (repeat1 == true)
{
repeat2 = true;
Console.WriteLine("Would you like to compare 2 numbers to see if their corresponding place is same total?");
gameAnswer = Console.ReadLine();
while (repeat2 == true)
{
if (gameAnswer == "yes" || gameAnswer == "yes" || gameAnswer == "YES")
{
Console.WriteLine("Please enter a three digit whole number");
string firstValue = Console.ReadLine();
int firstNumber = ValidInteger(firstValue);
Console.WriteLine("Please enter a second three digit whole number");
string secondValue = Console.ReadLine();
int secondNumber = ValidInteger(secondValue);
repeat1 = false;
repeat2 = false;
}
else if (gameAnswer == "no" || gameAnswer == "No" || gameAnswer == "NO")
{
Console.WriteLine("Okay, exiting now");
repeat1 = false;
repeat2 = false;
}
else
{
Console.WriteLine("I do not understnad what you have said");
repeat2 = false;
}
void Add(int firstNumber, int secondNumber)
{
int length1 = firstNumber.ToString().Length;
int length2 = secondNumber.ToString().Length;
string userInput;
if (length1 == length2)
{
string Answer = Convert.ToString(Compare(firstNumber, secondNumber, length1));
}
else
{
userInput = "invalid user input - Check number of digits next time.";
Console.WriteLine(userInput);
Console.ReadKey();
}
Console.ReadKey();
}
int ValidInteger(string digit1)
{
int value = 0;
string notInt = "This is not an integer.";
{
bool successfullyParsed = int.TryParse(digit1, out value);
if (successfullyParsed)
{
int firstNumber = Convert.ToInt32(value);
return value;
}
else
{
Console.WriteLine(notInt);
Console.ReadKey();
Environment.Exit(0);
return value;
}
}
}
string Compare(int a, int b, int c)
{
int lastDigitA;
int lastDigitB;
lastDigitA = (a % 10);
lastDigitB = (b % 10);
int sumStatic = lastDigitA + lastDigitB;
do
{
lastDigitA = (a % 10);
lastDigitB = (b % 10);
a = a / 10;
b = b / 10;
c--;
int sumCompare = lastDigitA + lastDigitB;
if (sumCompare != sumStatic)
{
Console.WriteLine("False");
return "False";
}
}
while (c != 0);
Console.WriteLine("True");
return "True";
}
}
}
}
}
}
From my understanding, it looks like you want the user to enter in three ints (with some input validation), and put the three ints through the Compare() function. If the function returns true, then say "True" to the console, and if it's false then say "False" to the console. If that's the case, I refactored your code into this (and it doesn't get stuck in a loop):
using System;
namespace DeliverablePart1
{
internal class DeliverablePart1
{
private static void Main(string[] args)
{
Console.WriteLine("Would you like to compare 2 numbers to see if their corresponding place is same total?");
var shouldContinue = Console.ReadLine();
if (shouldContinue != null && shouldContinue.Equals("yes", StringComparison.CurrentCultureIgnoreCase))
{
var firstNum = GetIntFromUser("Please enter a three digit whole number");
var secondNum = GetIntFromUser("Please enter a three digit whole number");
var thirdNum = GetIntFromUser("Please enter a three digit whole number");
Console.WriteLine(Compare(firstNum, secondNum, thirdNum) ? "True" : "False");
}
else
{
Console.WriteLine("Exiting");
}
// waits for the user to press a key to exit the app, so that they can see their result
Console.ReadKey();
}
/// <summary>
/// Makes the user enter in a three digit number, and exits if they say "no"
/// </summary>
/// <param name="msg">The message prompt to ask for the integer</param>
/// <returns>System.Int32., or will exit</returns>
public static int GetIntFromUser(string msg)
{
while (true)
{
Console.WriteLine(msg);
var valFromUser = Console.ReadLine()?.Trim();
if (valFromUser != null)
{
int result;
if (int.TryParse(valFromUser.Trim(), out result) && valFromUser.Length == 3)
{
return result;
}
if (valFromUser.Equals("no", StringComparison.CurrentCultureIgnoreCase))
{
Console.WriteLine("Exiting.");
Environment.Exit(0);
}
}
Console.WriteLine("Hmm, that's not a three digit number. Try again.");
}
}
public static bool Compare(int a, int b, int c)
{
var lastDigitA = a % 10;
var lastDigitB = b % 10;
var sumStatic = lastDigitA + lastDigitB;
do
{
lastDigitA = a % 10;
lastDigitB = b % 10;
a = a / 10;
b = b / 10;
c--;
var sumCompare = lastDigitA + lastDigitB;
if (sumCompare != sumStatic)
{
return false;
}
} while (c != 0);
return true;
}
}
}
I´m having trouble picking a random word from a list in another file.
Actually I can´t even get it to choose any word. I´m not sure how to connect the 2 files so to say.
Hoping someone can help out, I´m a beginner so please explain as easy as possible:)
I have 2 files, one is called program.cs and the other is called WordList.cs
I´m gonna paste all my code but first the little snip that I´m having problem with. I just can´t figure out how to write the code correct.
Here is the little part which is called Pick word:
//PICK WORD
static string pickWord()
{
string returnword = "";
TextReader file = new StreamReader(words);
string fileLine = file.ReadLine();
Random randomGen = new Random();
returnword = words[randomGen.Next(0, words.Count - 1)];
return returnword;
}
And here is all the code in Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
class Hangman
{
static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.Title = "C# Hangman";
Console.WriteLine("Welcome To C# Hangman!");
//MENU
int MenuChoice = 0;
while (MenuChoice != 4)
{
Console.Write("\n\t1) Add words");
Console.Write("\n\t2) Show list of words");
Console.Write("\n\t3) Play");
Console.Write("\n\t4) Quit\n\n");
Console.Write("\n\tChoose 1-4: "); //Choose meny item
MenuChoice = Convert.ToInt32(Console.ReadLine());
WordList showing = new WordList();
switch (MenuChoice)
{
case 1:
Console.Write("\n\tAdd a word\n\n");
var insert = Console.ReadLine();
showing.AddWord(insert);
Console.Write("\n\tList of words\n\n");
showing.ListOfWords();
break;
case 2:
Console.Write("\n\tList of words\n\n");
showing.ListOfWords();
break;
case 3: //Running game
int numGuessesInt = -1;
while (numGuessesInt == -1)
{
/* Sets the number of guesses the user has to guess the word*/
pickNumGuesses(ref numGuessesInt);
}
/* Randomly picks a word*/
string word = pickWord();
/* Creates a list of characters that will show */
List<char> guessedLetters = new List<char>();
bool solved = false;
while (solved == false)
{
/* Displaying a string to the user based on the user's correct guesses.
* If nothing is correct string will return "_ _ _ " */
string wordToDisplay = displayWord(guessedLetters, word);
/* If the string returned contains the "_" character, all the
* correct letters have not been guessed, so checking if user
* has lost, by checking if numGuessesLeft is less than 1.*/
if (!wordToDisplay.Contains("_"))
{
solved = true;
Console.WriteLine("You Win! The word was " + word);
/* Check if the user wants to play again. If they do,
* then solved is set to true, will end the loop,
* otherwise, checkIfPlayAgain will close the program.*/
checkIfPlayAgain();
}
else if (numGuessesInt <= 0)
{
solved = true;
Console.WriteLine("You Lose! The word was " + word);
checkIfPlayAgain();
}
else
{
/* If the user has not won or lost, call guessLetter,
* display the word, minus guesses by 1*/
guessLetter(guessedLetters, word, wordToDisplay, ref numGuessesInt);
}
}
break;
case 4:
Console.WriteLine("\n\tEnd game?\n\n");
break;
default:
Console.WriteLine("Sorry, invalid selection");
break;
}
}
}
// ****** PICK NUMBER OF GUESSES ******
static void pickNumGuesses(ref int numGuessesInt)
{
string numGuessesString = "";
Console.WriteLine("Pick a number of guesses");
numGuessesString = Console.ReadLine();
try
{
numGuessesInt = Convert.ToInt32(numGuessesString);
if (!(numGuessesInt <= 20 & numGuessesInt >= 1))
{
throw new Exception();
}
}
catch (Exception)
{
numGuessesInt = -1;
Console.WriteLine("Error: Invalid Number of Guesses");
}
}
//PICK WORD
static string pickWord()
{
string returnword = "";
TextReader file = new StreamReader(words);
string fileLine = file.ReadLine();
Random randomGen = new Random();
returnword = words[randomGen.Next(0, words.Count - 1)];
return returnword;
}
// ****** Display word ******
static string displayWord(List<char> guessedCharacters, string word)
{
string returnedWord = "";
if (guessedCharacters.Count == 0)
{
foreach (char letter in word)
{
returnedWord += "_ ";
}
return returnedWord;
}
foreach (char letter in word)
{
bool letterMatch = false;
foreach (char character in guessedCharacters)
{
if (character == letter)
{
returnedWord += character + " ";
letterMatch = true;
break;
}
else
{
letterMatch = false;
}
}
if (letterMatch == false)
{
returnedWord += "_ ";
}
}
return returnedWord;
}
// ****** Guess letter ******
static void guessLetter(List<char> guessedCharacters, string word, string wordToDisplay, ref int numGuessesLeft)
{
string letters = "";
foreach (char letter in guessedCharacters)
{
letters += " " + letter;
}
Console.WriteLine("Guess a letter");
Console.WriteLine("Guessed Letters: " + letters);
Console.WriteLine("Guesses Left: " + numGuessesLeft);
Console.WriteLine(wordToDisplay);
string guess = Console.ReadLine();
char guessedLetter = 'a';
try
{
guessedLetter = Convert.ToChar(guess);
if (!Char.IsLetter(guessedLetter))
{
throw new Exception();
}
}
catch (Exception)
{
Console.WriteLine("Error: Invalid Letter Choice");
//guessLetter(guessedCharacters, word, wordToDisplay, ref numGuessesLeft);
}
bool repeat = false;
for (int i = 0; i < guessedCharacters.Count; i++)
{
if (guessedCharacters[i] == guessedLetter)
{
Console.WriteLine("Error: Invalid Letter Choice");
repeat = true;
//guessLetter(guessedCharacters, word, wordToDisplay, ref numGuessesLeft);
}
}
if (repeat == false)
{
guessedCharacters.Add(guessedLetter);
numGuessesLeft -= 1;
}
}
// ****** Check to see if player wants to play again. ******
static void checkIfPlayAgain()
{
Console.WriteLine("Would you like to play again? (y/n)");
string playAgain = Console.ReadLine();
if (playAgain == "n")
{
Environment.Exit(1);
}
}
}
And here is the code for WordList.cs
using System;
using System.Collections.Generic;
class WordList
{
List <string> words = new List<string>();
public void ListOfWords()
{
words.Add("test"); // Contains: test
words.Add("dog"); // Contains: test, dog
words.Insert(1, "shit"); // Contains: test, shit, dog
words.Sort();
foreach (string word in words) // Display for verification
{
Console.WriteLine(word);
}
}
public void AddWord(string value){
words.Add(value);
}
}
I have made some changes to your code. The code works now but is far from perfect.
Your solution has two files Program.cs and Wordlist.cs, which looks like this
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
public class Hangman
{
/*
* Some notes on your code:
* use naming convention for methods and fields, i.e. methods names start with a capital letter
* use modifiers for methods, i.e private, public, protected in your method declarations
* make variables private if you use them on several methods
* and finally: read a book on c#
*
*/
private static WordList words;
private static Random randomGen = new Random();
public static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.Title = "C# Hangman";
Console.WriteLine("Welcome To C# Hangman!");
initializeWordList();
//MENU
int MenuChoice = 0;
while (MenuChoice != 4)
{
Console.Write("\n\t1) Add words");
Console.Write("\n\t2) Show list of words");
Console.Write("\n\t3) Play");
Console.Write("\n\t4) Quit\n\n");
Console.Write("\n\tChoose 1-4: "); //Choose meny item
MenuChoice = Convert.ToInt32(Console.ReadLine());
switch (MenuChoice)
{
case 1:
Console.Write("\n\tAdd a word\n\n");
var insert = Console.ReadLine();
words.Add(insert);
Console.Write("\n\tList of words\n\n");
foreach (string w in words) // Display for verification
Console.WriteLine(w);
break;
case 2:
Console.Write("\n\tList of words\n\n");
foreach (string w in words) // Display for verification
Console.WriteLine(w);
break;
case 3: //Running game
int numGuessesInt = -1;
while (numGuessesInt == -1)
{
/* Sets the number of guesses the user has to guess the word*/
pickNumGuesses(ref numGuessesInt);
}
/* Randomly picks a word*/
string word = PickWord();
/* Creates a list of characters that will show */
List<char> guessedLetters = new List<char>();
bool solved = false;
while (solved == false)
{
/* Displaying a string to the user based on the user's correct guesses.
* If nothing is correct string will return "_ _ _ " */
string wordToDisplay = displayWord(guessedLetters, word);
/* If the string returned contains the "_" character, all the
* correct letters have not been guessed, so checking if user
* has lost, by checking if numGuessesLeft is less than 1.*/
if (!wordToDisplay.Contains("_"))
{
solved = true;
Console.WriteLine("You Win! The word was " + word);
/* Check if the user wants to play again. If they do,
* then solved is set to true, will end the loop,
* otherwise, checkIfPlayAgain will close the program.*/
checkIfPlayAgain();
}
else if (numGuessesInt <= 0)
{
solved = true;
Console.WriteLine("You Lose! The word was " + word);
checkIfPlayAgain();
}
else
{
/* If the user has not won or lost, call guessLetter,
* display the word, minus guesses by 1*/
guessLetter(guessedLetters, word, wordToDisplay, ref numGuessesInt);
}
}
break;
case 4:
Console.WriteLine("\n\tEnd game?\n\n");
break;
default:
Console.WriteLine("Sorry, invalid selection");
break;
}
}
}
private static void initializeWordList()
{
words = new WordList();
words.Add("test"); // Contains: test
words.Add("dog"); // Contains: test, dog
words.Insert(1, "shit"); // Contains: test, shit, dog
words.Sort();
}
// ****** PICK NUMBER OF GUESSES ******
private static void pickNumGuesses(ref int numGuessesInt)
{
string numGuessesString = "";
Console.WriteLine("Pick a number of guesses");
numGuessesString = Console.ReadLine();
try
{
numGuessesInt = Convert.ToInt32(numGuessesString);
if (!(numGuessesInt <= 20 & numGuessesInt >= 1))
{
throw new Exception();
}
}
catch (Exception)
{
numGuessesInt = -1;
Console.WriteLine("Error: Invalid Number of Guesses");
}
}
//PICK WORD
private static string PickWord()
{
return words[randomGen.Next(0, words.Count() - 1)];
}
// ****** Display word ******
private static string displayWord(List<char> guessedCharacters, string word)
{
string returnedWord = "";
if (guessedCharacters.Count == 0)
{
foreach (char letter in word)
{
returnedWord += "_ ";
}
return returnedWord;
}
foreach (char letter in word)
{
bool letterMatch = false;
foreach (char character in guessedCharacters)
{
if (character == letter)
{
returnedWord += character + " ";
letterMatch = true;
break;
}
else
{
letterMatch = false;
}
}
if (letterMatch == false)
{
returnedWord += "_ ";
}
}
return returnedWord;
}
// ****** Guess letter ******
static void guessLetter(List<char> guessedCharacters, string word, string wordToDisplay, ref int numGuessesLeft)
{
string letters = "";
foreach (char letter in guessedCharacters)
{
letters += " " + letter;
}
Console.WriteLine("Guess a letter");
Console.WriteLine("Guessed Letters: " + letters);
Console.WriteLine("Guesses Left: " + numGuessesLeft);
Console.WriteLine(wordToDisplay);
string guess = Console.ReadLine();
char guessedLetter = 'a';
try
{
guessedLetter = Convert.ToChar(guess);
if (!Char.IsLetter(guessedLetter))
{
throw new Exception();
}
}
catch (Exception)
{
Console.WriteLine("Error: Invalid Letter Choice");
//guessLetter(guessedCharacters, word, wordToDisplay, ref numGuessesLeft);
}
bool repeat = false;
for (int i = 0; i < guessedCharacters.Count; i++)
{
if (guessedCharacters[i] == guessedLetter)
{
Console.WriteLine("Error: Invalid Letter Choice");
repeat = true;
//guessLetter(guessedCharacters, word, wordToDisplay, ref numGuessesLeft);
}
}
if (repeat == false)
{
guessedCharacters.Add(guessedLetter);
numGuessesLeft -= 1;
}
}
// ****** Check to see if player wants to play again. ******
static void checkIfPlayAgain()
{
Console.WriteLine("Would you like to play again? (y/n)");
string playAgain = Console.ReadLine();
if (playAgain == "n")
{
Environment.Exit(1);
}
}
}
Wordlist.cs
using System;
using System.Collections.Generic;
public class WordList : List<string>
{
}
Here is the very simple solution:
Populate your list just one time, or when ever you add any word, call this method. Code:
private void PopulateTheWordList()
{
Console.Write("\n\tAdd a word\n\n");
WordList.Add(Console.ReadLine());
}
Now just call this method to get random words:
private string PickWord()
{
Random ran = new Random();
return WordList[ran.Next(0, WordList.Count)];
}
If you need to create List of words in another class, then use keyword static:
static List<string> WordList = new List<string>();
Now you can call it by just writing the class name, like YourClassName.WordList
Try creating a Static Class and add a method for returning your List, you will then be able to access your wordlist.
example:
static class WordList
{
static List<string> words = new List<string>();
public static void ListOfWords()
{
words.Add("test"); // Contains: test
words.Add("dog"); // Contains: test, dog
words.Insert(1, "shit"); // Contains: test, shit, dog
words.Sort();
foreach (string word in words) // Display for verification
{
Console.WriteLine(word);
}
}
public static List<string> GetWords()
{
return words;
}
public static void AddWord(string value)
{
words.Add(value);
}
}
You would then change your switch statement to look something like this.
switch (MenuChoice)
{
case 1:
Console.Write("\n\tAdd a word\n\n");
var insert = Console.ReadLine();
WordList.AddWord(insert);
Console.Write("\n\tList of words\n\n");
WordList.ListOfWords();
break;
case 2:
Console.Write("\n\tList of words\n\n");
WordList.ListOfWords();
break;
....
and your pickWord Method would look like this:
static string pickWord()
{
string returnword = "";
Random randomGen = new Random();
returnword = WordList.GetWords()[randomGen.Next(0, WordList.GetWords().Count() - 1)];
return returnword;
}
I modified your Wordlist class so that it can use a file to maintain your Words between uses of your program, just incase that is what was being asked of you.
static class WordList
{
static string filePath = #"C:\temp\Word.txt";
static List<string> words = new List<string>();
private static void CheckFile()
{
//Makes sure our base words are saved to the file
if (!File.Exists(#"C:\temp\Word.txt"))
{
using (TextWriter writer = new StreamWriter(filePath))
{
writer.WriteLine("test");
writer.WriteLine("dog");
writer.WriteLine("shit");
}
}
}
public static void ListOfWords()
{
CheckFile();
words.Clear();
using (TextReader file = new StreamReader(filePath))
{
char[] delineators = new char[] { '\r', '\n' };
string[] tempWords = file.ReadToEnd().Split(delineators, StringSplitOptions.RemoveEmptyEntries);
foreach (string line in tempWords)
{
words.Add(line);
}
}
foreach (string word in words) // Display for verification
{
Console.WriteLine(word);
}
}
public static List<string> GetWords()
{
return words;
}
public static void AddWord(string value)
{
CheckFile();
using (TextWriter writer = new StreamWriter(filePath,true ))
{
writer.WriteLine(value);
}
}
}
I have two words:
Source: John
ConvertTo: Jack
and I want to show the effect of convert all letters from "Source" at the same time to the "ConvertTo" word. I already create a program to accomplish that but processing one letter at a time, to show the effect I use Threads, the thing is that to process all letters at the same time I suppose I need one thread per letter, and every thread will call the same function that process the letter, and I use global variables.
Here is the code (works only for texts with same lenght):
private void button1_Click(object sender, EventArgs e)
{
lblResult.Text = "";
lblResult2.Text = "";
ThreadPool.QueueUserWorkItem(new WaitCallback(Process));
}
int movement = 0;
string CumulateText;
private void Process(object stateinfo)
{
int value;
int operation; //0->[+] 1->[-]
CumulateText = "";
for (int i = 0; i <= textBox1.Text.Length - 1; i++)
{
if (textBox1.Text[i] != ' ')
{
value = (char)textBox1.Text[i] - (char)textBox2.Text[i];
if (value >= 0)
operation = 1;
else
operation = 0;
for (int ii = 0; ii <= Math.Abs(value); ii++)
{
if (operation == 1)
movement = (char)textBox1.Text[i] - ii;
else
movement = (char)textBox1.Text[i] + ii;
this.Invoke(new EventHandler(ShowMovement));
System.Threading.Thread.Sleep(10);
}
}
CumulateText += textBox2.Text[i].ToString();
}
}
private void ShowMovement(object sender, EventArgs e)
{
lblResult.Text = CumulateText + Convert.ToString((char)movement);
}
I hope I made myself understood.
please any advise to accomplish that.
thanks
To clarify more what I want to accomplish here is an example:
Source: John
ConvertTo: Jack
J - same J
o - decrease till a (o, n, m, ..., a)
h - decrease till c (h, g, f, ..., c)
n - decrease till k (n, m, l, k)
I once had to do something similar for a small little project I was working on for fun.
I do not see why you would need to create a thread for each letter to create a transition between two words unless I'm not understanding what you are pretending to do correctly.
Check and study the following code, see if its any help:
static class Program
{
static void Main()
{
TextTranstition transition = new TextTranstition();
transition.TransitionFinished += TransitionTicked;
transition.TransitionTicked += TransitionTicked;
transition.StartTransition("AmazingWordTransition", "MyNewWordAppearing", 100);
Thread.CurrentThread.Join();
Console.ReadKey();
}
public static void TransitionTicked(object sender, TranstitionEventArgs e)
{
Console.Clear();
Console.Write(e.TransitionText);
}
}
public class TranstitionEventArgs : EventArgs
{
private readonly string transitionText;
public string TransitionText { get { return this.transitionText; } }
public TranstitionEventArgs(string transitionText)
{
this.transitionText = transitionText;
}
}
public class TextTranstition
{
private struct StartInfo
{
public StartInfo(string initialText, string finalText, int timeStep)
{
this.initialText = initialText;
this.finalText = finalText;
this.timeStep = timeStep;
}
private readonly string initialText;
public string InitialText { get { return this.initialText; } }
private readonly string finalText;
public string FinalText { get { return this.finalText; } }
private readonly int timeStep;
public int TimeStep { get { return this.timeStep; } }
}
public EventHandler<TranstitionEventArgs> TransitionFinished;
public EventHandler<TranstitionEventArgs> TransitionTicked;
public void StartTransition(string initialText, string finalText, int timeStep)
{
StartInfo startInfo = new StartInfo(initialText, finalText, timeStep);
Thread t = new Thread(startTransition);
t.Start(startInfo);
}
private void startTransition(object info)
{
StartInfo startInfo = (StartInfo)info;
string initialText = startInfo.InitialText;
string finalText = startInfo.FinalText;
if (initialText.Length < finalText.Length)
{
initialText = initialText.PadRight(finalText.Length);
}
if (TransitionTicked != null) TransitionTicked(this, new TranstitionEventArgs(initialText));
while ((initialText = transition(initialText, finalText)) != finalText)
{
Thread.Sleep(startInfo.TimeStep);
if (TransitionTicked != null) TransitionTicked(this, new TranstitionEventArgs(initialText));
}
if (TransitionFinished != null) TransitionFinished(this, new TranstitionEventArgs(finalText));
}
private string transition(string initialText, string finalText)
{
StringBuilder b = new StringBuilder(finalText.Length);
for (int i = 0; i < finalText.Length; i++)
{
char c = initialText[i];
int charCode = (int)c;
if (c != finalText[i])
{
if (charCode == 122 || charCode==32) charCode = 65;
else if (charCode == 90) charCode = 97;
else
{
charCode += 1;
}
}
b.Append((char)charCode);
}
return b.ToString();
}
}
Use BackgroudWorker for this kind of stuff.
I want to convert following javascript function to c#
can anyone help?
function parseCoordinate(coordinate,type,format,spaced) {
coordinate = coordinate.toString();
coordinate = coordinate.replace(/(^\s+|\s+$)/g,''); // remove white space
var neg = 0; if (coordinate.match(/(^-|[WS])/i)) { neg = 1; }
if (coordinate.match(/[EW]/i) && !type) { type = 'lon'; }
if (coordinate.match(/[NS]/i) && !type) { type = 'lat'; }
coordinate = coordinate.replace(/[NESW\-]/gi,' ');
if (!coordinate.match(/[0-9]/i)) {
return '';
}
parts = coordinate.match(/([0-9\.\-]+)[^0-9\.]*([0-9\.]+)?[^0-9\.]*([0-9\.]+)?/);
if (!parts || parts[1] == null) {
return '';
} else {
n = parseFloat(parts[1]);
if (parts[2]) { n = n + parseFloat(parts[2])/60; }
if (parts[3]) { n = n + parseFloat(parts[3])/3600; }
if (neg && n >= 0) { n = 0 - n; }
if (format == 'dmm') {
if (spaced) {
n = Degrees_to_DMM(n,type,' ');
} else {
n = Degrees_to_DMM(n,type);
}
} else if (format == 'dms') {
if (spaced) {
n = Degrees_to_DMS(n,type,' ');
} else {
n = Degrees_to_DMS(n,type,'');
}
} else {
n = Math.round(10000000 * n) / 10000000;
if (n == Math.floor(n)) { n = n + '.0'; }
}
return comma2point(n);
}
}
Check out Regex on MSDN or have a quick look on google for Regex C#
if (coordinate.match(/(^-|[WS])/i)) { neg = 1; }
would become:
using System.Text.RegularExpressions;
Regex myRegex = new Regex("/(^-|[WS])/i)");
if (coordinate.IsMatch(myRegex))
{
neg=1;
}
If it will always be like your above example 'N27 53.4891' then you could store it as a string. If the above latitude is in 2 parts ('N27' and 53.4891) and you need to access them seperately then you could have a custom Coordinate class, e.g.
public class coordinate
{
public string otherPart {get; set;} // N27
public float coordPart {get; set;} // 53.4891
}
You can then override the .toString() method to get 'N27 53.4891'.
Regex myPattern =new Regex("/(^-|[WS])/i)");
if(myPattern.isMatch(coordinate))
{ neg = 1; }
see if this works