My values are changing by changing the position of methods - c#

I'm working on c# to make a program for checking vowels,consonants,characters,words and number of sentences using method for each)
. My program is working good but my
problem is changing the places of method where I applied them chance the values.
Here is the program
on method characters I use the method words (whick basically counts the spaces ) same for Consonants
the problem is I need to apply the methods on main accourding to the order I have created them "Words>Sentences>Vowels>Characters>COnsonants"
If I chnage the order I get the wrong answer
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Task_Raza_Class
{
class Program
{
static void Main(string[] args)
{
string state;
Console.WriteLine("Enter an Statement / Sentance \nPress Enter to Continue..");
state = Console.ReadLine();
raza task = new raza();
// Words>Sentances>Vowels>Characters>COnsonents
Console.WriteLine("Words"+task.words(state));
Console.WriteLine("No of Sentances"+task.tances(state));
Console.WriteLine("Vowels"+task.vowels(state));
Console.WriteLine("Characters"+task.characters(state));
Console.WriteLine("Consonents"+task.consonents(state));
Console.ReadKey();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Task_Raza_Class
{
class raza
{
public int cw , cv , cc , cp , cchar ;
public raza()
{
cw = 1; cv = cc = cp = cchar = 0;
}
public int words(string state)
{
char[] s_arr = new char[200];
s_arr = state.ToCharArray();
for (int i = 0; i < s_arr.Length; i++)
{
if(s_arr[i]==' ')
{
cw++;
}
}
return (cw);
}
public int tances(string state)
{
char[] s_arr = new char[200];
s_arr = state.ToCharArray();
for (int i = 0; i < s_arr.Length; i++)
{
if (s_arr[i] == '.')
{
cp++;
}
}
return (cp);
}
public int vowels(string state)
{
char[] s_arr = new char[200];
s_arr = state.ToCharArray();
for (int i = 0; i < s_arr.Length; i++)
{
if (s_arr[i] == 'a' || s_arr[i] == 'A' || s_arr[i] == 'e' || s_arr[i] == 'E' || s_arr[i] == 'i' || s_arr[i] == 'I' || s_arr[i] == 'o' || s_arr[i] == 'O' || s_arr[i] == 'u' || s_arr[i] == 'U')
{
cv++;
}
}
return (cv);
}
public int characters(string state)
{
char[] s_arr = new char[200];
s_arr = state.ToCharArray();
cchar = s_arr.Lenght - words(state)-1
return (cchar);
}
public int consonents(string state)
{
char[] s_arr = new char[200];
s_arr = state.ToCharArray();
cc = characters(state)-vowels(state);
return (cc);
}
}
}

The problem is cchar and cv are member fields, whose values are maintained between calls. Because consonents calls characters and vowels, those two functions get called twice and on the 2nd time will have whatever value was left over from the first call. There's no need for any member fields in your raza class - they can all be local variables. Alternatively, you could design raza to accept the state parameter in the constructor, then call characters and consonents and change vowels to reuse the values from cchar and cv.
(BTW the correct English spelling is "consonants" and "sentences")

Related

Save and load a game by using StreamWriter and ReadWriter (C#)

I'm creating a small program which can save and load char array values. Then, I got stuck with two problems.
I have no idea how to make the program end after saving the data.
After loading the char array, it looks the game starts where I saved last time. However, when I put "#" on the place where is already marked, it is accepted. (It is supposed to display error message)
This is when I start new game.
It displays error message properly.
Here is class which includes streamWriter and streamReader.
public class History
{
public char QUIT = 'Y';
public char CONTINUE = 'N';
public char inputGameContinue;
public void WriteFile(char []arr)
{
FileStream sb = new FileStream("MyFile.txt", FileMode.OpenOrCreate);
StreamWriter sw = new StreamWriter(sb);
WriteLine("If you want to save the data, enter" + QUIT +"| To continue, enter "+CONTINUE );
inputGameContinue = char.Parse(ReadLine());
if(inputGameContinue=='Y')
{
sw.Write(arr);
WriteLine("The data is saved!");
}
sw.Close();
}
public void ReadFile()
{
string path = "MyFile.txt";
WriteLine("New game? >> 1 | Load saved data? >>2 ");
int command = int.Parse(ReadLine());
if (command == 2)
{
using (StreamReader sr = new StreamReader(path))
{
while (sr.Peek() >= 0)
{
WriteLine(sr.ReadLine());
}
}
}
}
}
Class2
using System;
using static System.Console;
using System.IO;
namespace createSample
{
public class writeRead
{
public static void Main(string[] args)
{
InputClass inputClass = new InputClass();
ArrayValue arrayValue = new ArrayValue();
History history = new History();
WriteLine("Welcome to game!");
WriteLine("");
history.ReadFile();
do
{
inputClass.inputNumber();
while (true)
{
if (arrayValue.arr[inputClass.input] == '#')
{
WriteLine("{0} already marked '#'. Try another.", inputClass.input);
inputClass.inputNumber();
}
else
{
arrayValue.arr[inputClass.input] = '#';
arrayValue.printArray();
history.WriteFile(arrayValue.arr);
break;
}
}
}
while (checkWhenFinish(arrayValue)!=1 );
WriteLine("All letters are marked with '#'");
Read();
}
public static int checkWhenFinish(ArrayValue a)
{
if(a.arr[0] != '0' && a.arr[1] != '1' && a.arr[2] != '2' && a.arr[3] != '3' && a.arr[4] != '4')
{
return 1;
}
else
{
return 0;
}
}
}
}
Class3
using System;
using System;
using System.Numerics;
using System.Reflection.Emit;
using static System.Console;
using System.IO;
namespace createSample
{
public class ArrayValue
{
public char []arr = { '0','1', '2', '3', '4' };
public void printArray()
{
WriteLine("{0},{1},{2},{3},{4}", arr[0], arr[1], arr[2], arr[3], arr[4]);
}
}
}
Class 4
using System;
using System;
using System.Numerics;
using System.Reflection.Emit;
using static System.Console;
using System.IO;
namespace createSample
{
public class InputClass
{
public int input;
public void inputNumber()
{
while (true)
{
Write("Enter number ? (0 to 4) >> ");
if (!int.TryParse(ReadLine(), out input))
{
input = -1;
}
if (input == 0|| input == 1 || input == 2 || input == 3 || input == 4 )
{
break;
}
else
{
WriteLine("Error! Try again!");
}
}
}
}
}
The problem is when you call history.ReadFile() it can read the file and display its contents, but it never updates arrayValue.arr so when the check is done later, arrayValue.arr[inputClass.input] is still 2.
You might want to pass in arrayValue by reference to ReadFile() to have it updated:
history.ReadFile(ref arrayValue);
then in History
public void ReadFile(ref ArrayValue arrayValue)
{
...
while (sr.Peek() >= 0)
{
var line = sr.ReadLine();
WriteLine(line);
for (int i = 0; i < arrayValue.arr.Length; i++)
{
arrayValue.arr[i] = line[i];
}
}
...
}

Balanced Brackets using Array Stack in C#

I'm trying to make a program in C# to decide weather Brackets are balanced or not..
After some work i made it using Array Stack and it's working but i have 2 problems:
1) if i entered brackets like this way "()[]{}(())" it shall work
i.e ("I must start with only ( [ {") but if i started the string
with ("})]") it will always says unbalanced even if it was... so I'm
asking if someone could give me a hint for solution.
2) Is there a better way for Pop method cause the else condition is
just annoying me and if i removed it, it will no longer work
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Balanced_Brackets
{
class Program
{
public static bool IsBalanced(string brackets)
{
bool balanced = false;
MyStack s = new MyStack();
foreach (var item in brackets)
{
if (item == '(' || item == '[' || item == '{')
s.Push(item);
else if (item == ')' || item == ']' || item == '}')
{
var poped = s.Pop();
if (poped == '(' && item == ')')
balanced = true;
else if (poped == '[' && item == ']')
balanced = true;
else if (poped == '{' && item == '}')
balanced = true;
else
return balanced = false;
}
}
if (balanced == true)
return true;
else
return false;
}
static void Main(string[] args)
{
string Brackets = Console.ReadLine();
IsBalanced(Brackets);
if (IsBalanced(Brackets))
Console.Write("Balanced");
else
Console.Write("Un-Balanced");
Console.ReadKey();
}
}
class MyStack
{
char[] exp = new char[5];
public int top = -1;
public bool IsEmpty()
{
return (top == -1);
}
public bool IsFull()
{
return (top == exp.Length - 1);
}
public void Push(char a)
{
if (!IsFull())
exp[++top] = a;
}
public char Pop()
{
if (!IsEmpty())
return exp[top--];
else
return ' ';
}
}
}

Check ReadKey only for letters (alphabet) in string

i am doing game "Hangman" but i have a problem. I am using ReadKey to find the guess of player, but he can use even numbers or buttons like "Enter" etc. I want to stop this, but i don't know how :/ Can you help me please? I want control, if in result of ReadKey is letter from alphabet or no (but it must be in "string" format, cuz i am working later with string). Thank you very much guys, here is my code :)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Hangman
{
class MainClass
{
/// <summary>
/// Hra Oběšenec
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
Console.WriteLine("Vítejte ve hře Oběšenec!");
//List slov, které bude hráč hádat
string[] words = new string[5];
words[0] = "car";
words[1] = "school";
words[2] = "apple";
words[3] = "orange";
words[4] = "xamarin";
//Získávám délku slova (hádaného slova)
for (int X = 0; X < words.Length; X++)
{
string guessWord = words[X];
short lifes = 5;
short guessedLetters = 0;
char GuessingLetter;
char[] lettersOfWord = new char[guessWord.Length];
//
for (int I = 0; I < guessWord.Length; I++)
{
//Length of word is changing to *
lettersOfWord[I] = '*';
}
bool InGame = true;
//When this while is true, the game is still going, when it will be false, the game will end
while (InGame)
{
//Ochrana proti špatnému inputu
try
{
Console.WriteLine(lettersOfWord);
Console.WriteLine("Stiskněte klávesu. Životy:" + lifes);
ConsoleKeyInfo result_guess = Console.ReadKey(true);
string result = result_guess.KeyChar.ToString();
if (result.Length == 0)
{
continue;
}
//Hráč hádá slovo
GuessingLetter = result[0];
lifes--;
for (int I = 0; I < lettersOfWord.Length; I++)
{
if (lettersOfWord[I] == '*')
{
//Pokud hráč uhádne písmenko ve slově
if (guessWord[I] == GuessingLetter)
{
lettersOfWord[I] = GuessingLetter;
guessedLetters++;
lifes++;
Console.WriteLine("Správně!");
}
}
}
}
catch (Exception e)
{
Console.WriteLine("Nastala neočekávaná chyba!" + e);
}
//Pokud prohraje(promrhá všechny pokusy) hra skončí, avšak pokud slovo uhádne (a zůstane alespoň jeden život) vyhrál hru
if (lifes== 0 || guessedLetters == guessWord.Length)
{
//Konec hry
InGame = false;
if (lifes == 0)
{
Console.WriteLine("Smůla prohrál jsi!");
Console.ReadKey();
break;
}
else
{
//Vítězství nad levlem
Console.WriteLine("Uhodnul jsi celé slovo! Gratuluji!!");
}
}
}
}
}
}
}
Check if the keychar is a letter with the IsLetter method and keep asking for letters if it doesn't. Something like this:
private char GetLetter()
{
while (true)
{
Console.WriteLine("Please input a letter.");
var character = Console.ReadKey().KeyChar;
if (char.IsLetter(character))
return character;
}
}

C# for case in string(easy)

so I have this code. I need to generate a for loop that checks all the characters in the string and checks if they are all valid(So numbers from 0->7). But I don't know how to write it, I tried something but it didn't work. Here are the examples:user enters: 77, code works, user enters 99, code doesn't work, user enters 5., code doesn't work, etc..
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NALOGA1
{
class Program
{
static string decToOct(int stevilo)//v mojon primere 7
{
string izhod = "";
//7>0 DRŽI
while (stevilo > 0)
{
//izhodi se dodeli ostanek deljenja z 8 keri se spremeni v string
izhod = (stevilo % 8) + izhod;
//7/8;
stevilo /= 8;
}
return izhod;
}
static int Octtodesetisko(string stevilo)
{
double vsota = 0;
for (int i = stevilo.Length - 1; i >= 0; i--)
{
int stevka = stevilo[i] - '0';
vsota += (stevka * Math.Pow(8, i));
}
return (int)vsota;
}
static void Main(string[] args)
{
//3 podprogram-in progress
string prvastevilka = Console.ReadLine();
int prvasprememba = Int32.Parse(prvastevilka);
if (prvasprememba > 0)
{
Console.WriteLine(decToOct(prvasprememba));
}
else
{
Console.WriteLine("Napaka");
}
string drugastevilka = Console.ReadLine();
int drugasprememba = Octtodesetisko(drugastevilka);
foreach (char znak in drugastevilka)
{
if(znak!=1 || znak!=2 || znak!=3 || znak!=4 || znak!=5 || znak!=6 || znak!=7)
{
Console.WriteLine("Napaka");
}
else
{
Console.WriteLine("dela :D");
}
}
Console.ReadKey();
}
}
}
Personally, I would take advantage of the LINQ Enumerable.All method to express this in a very concise and readable way:
if (str.Any() && str.All(c => c >= '0' && c <= '7'))
{
Console.WriteLine("good");
}
else
{
Console.WriteLine("bad");
}
EDIT: No LINQ
It's not hard to translate what the LINQ Enumerable.All method does to a normal loop. It's just more verbose:
bool isValid = true;
foreach (char c in str)
{
if (c < '0' || c > '7')
{
isValid = false;
break;
}
}
if (str.Length != 0 && isValid)
{
Console.WriteLine("good");
}
else
{
Console.WriteLine("bad");
}
Firstly, there seems to be a mistake in the line
if(znak!=1 || znak!=2 || znak!=3 || znak!=4 || znak!=5 || znak!=6 || znak!=7)
I guess it should read
if(znak!='1' || znak!='2' || znak!='3' || znak!='4' || znak!='5' || znak!='6' || znak!='7')
which should be compressed to
if (znak >= '0' && znak <= '7')
You can use linq instead of the for loop here like this:
if (drugastevilka.All(c => c >= '0' && c <= '7')
Console.WriteLine("dela :D");
else
Console.WriteLine("Napaka");
But the best solution is probably to use a regular expression:
Regex regex = new Regex("^[0-7]+$");
if (regex.IsMatch(drugastevilka))
Console.WriteLine("dela :D");
else
Console.WriteLine("Napaka");
Edit: the linq solution shown accepts empty strings, the regex (as shown) needs at least 1 character. Exchange the + with a * and it will accept empty strings, too. But I don't think you want to accept empty strings.
You are messing up with the datatype
Can you try with below code
static string decToOct(int stevilo)//v mojon primere 7
{
int izhod = 0;
//7>0 DRŽI
while (stevilo > 0)
{
//izhodi se dodeli ostanek deljenja z 8 keri se spremeni v string
izhod = (stevilo % 8) + izhod;
//7/8;
stevilo /= 8;
}
return (izhod.ToString());
}
What about something like this?
class Program
{
static void Main(string[] args)
{
string someString = "1234567";
string someOtherString = "1287631";
string anotherString = "123A6F2";
Console.WriteLine(IsValidString(someString));
Console.WriteLine(IsValidString(someOtherString));
Console.WriteLine(IsValidString(anotherString));
Console.ReadLine();
}
public static bool IsValidString(string str)
{
bool isValid = true;
char[] splitString = str.ToCharArray(); //get an array of each character
for (int i = 0; i < splitString.Length; i++)
{
try
{
double number = Char.GetNumericValue(splitString[i]); //try to convert the character to a double (GetNumericValue returns a double)
if (number < 0 || number > 7) //we get here if the character is an int, then we check for 0-7
{
isValid = false; //if the character is invalid, we're done.
break;
}
}
catch (Exception) //this will hit if we try to convert a non-integer character.
{
isValid = false;
break;
}
}
return isValid;
}
}
IsValidString() takes a string, converts it to a Char array, then checks each value as such:
Get the numeric value
Check if the value is between 0-7
GetNumericValue will fail on a non-integer character, so we wrap it in a try/catch - if we hit an exception we know that isValid = false, so we break.
If we get a valid number, and it's not between 0-7 we also know that isValid = false, so we break.
If we make it all the way through the list, the string is valid.
The sample given above returns:
IsValidString(someString) == true
IsValidString(someOtherString) == false
IsValidString(anotherString) == false

How to append sounds in C#

I am studying C# by myself by reading some books and watching some tutorials. So, i decided to make a small project at the same time, to get more experience and harden my knowledge. I am trying to create a text to speech program in Georgian(my language) but, i couldn't understand how to append different sounds to each other. For example, when my program wants to say "language" it will divide the word to "la" "n" "gu" "a" "ge" so, i have recorded these parts and want to append them and create a word. I looked for classes on MSDN.COM and found SoundPlayer but, i couldn't figure out how to append the sounds of WAV format. i want to add one sound to another and play a new one, for example i have sound that says "aaa" and the other says "bbbb" i want to get a sound that says "aaabbbb".
To divide words i created an arraylist and used this code.
public ArrayList divide(String s) //დაყოფა და arraylist-ში გადანაწილება
{
ArrayList a = new ArrayList();
int i = 0;
while (i < s.Length)
{
if (s[i] == ',' || s[i] == ' ' || s[i] == '.')
{
a.Add(s.Substring(i, i + 1));
i++;
continue;
}
if (consonant(s[i]) && (i + 1) != s.Length && sonant(s[i + 1]))
{
if (isFirstSonant(s, i))
a.Add(s.Substring(i, i + 2) + "_FIRST");
else
a.Add(s.Substring(i, i + 2) + "_SECOND");
i += 2;
continue;
}
if (sonant(s[i]) && ((i + 1) < s.Length && sonant(s[i]) || i == (s.Length - 1)))
{
if (isFirstSonant(s, i))
a.Add(s.Substring(i, i + 1) + "_FIRST");
else
a.Add(s.Substring(i, i + 1) + "_SECOND");
i++;
continue;
}
if (consonant(s[i]) && ((i + 1) < s.Length && consonant(s[i]) || i == (s.Length - 1)))
{
a.Add(s.Substring(i, i + 1) + "_SECOND");
i++;
continue;
}
}
return a;
}
I have made this program on java and want to do the same on C# so this is my code on java.
this is how i appended the sounds after, putting them in arraylist.
public AudioInputStream append(AudioInputStream main, String s) throws UnsupportedAudioFileException, IOException {
return new AudioInputStream(
new SequenceInputStream(main, find(s)),
main.getFormat(),
main.getFrameLength() + find(s).getFrameLength());
}
private String s;
public void Process() {
try {
AudioInputStream main = AudioSystem.getAudioInputStream(new File("C:/Users/Vato/Desktop/Programing/sintezatori/alphabet/blank.wav"));
ArrayList<String> aa = divide(s);
for(int ii=0;ii<aa.size();ii++) {
main=append(main, aa.get(ii));
System.out.println(aa.get(ii));
}
AudioSystem.write(main, AudioFileFormat.Type.WAVE, new File("C:/Users/Vato/Desktop/Programing/sintezatori/alphabet/result.wav"));
result=main;
AudioInputStream result1 = AudioSystem.getAudioInputStream(new File("C:/Users/Vato/Desktop/Programing/sintezatori/alphabet/result.wav"));
DataLine.Info info =
new DataLine.Info(Clip.class,
result1.getFormat());
Clip clip = (Clip) AudioSystem.getLine(info);
clip.open(result1);
clip.start();
} catch (Exception e) {
e.printStackTrace();
}
}
private AudioInputStream result;
public AudioInputStream getResult() {
return result;
}
Which method or class should i use from these http://msdn.microsoft.com/en-us/library/system.media.soundplayer.aspx ?
How can i do the same in C#?
If you don't want to use an existing SDK you could do something like the following:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Media;
using System.Text;
namespace ConsoleApplication3
{
public class SpeechClass
{
private Dictionary<char, string> _letterToFileMapping = new Dictionary<char, string>();
private string _basePath = "\\soundfiles";
public SpeechClass()
{
PopulateMappings();
}
private void PopulateMappings()
{
_letterToFileMapping.Add('a', "asound.wav");
_letterToFileMapping.Add('b', "bsound.wav");
_letterToFileMapping.Add('c', "csound.wav");
_letterToFileMapping.Add('d', "dsound.wav");
}
private void SayWord(string word)
{
var chars = word.ToCharArray();
List<string> filestosay = new List<string>();
foreach (var c in chars)
{
string sound;
if(_letterToFileMapping.TryGetValue(c, out sound))
{
filestosay.Add(sound);
}
}
foreach (string s in filestosay)
{
SoundPlayer p = new SoundPlayer();
p.SoundLocation = Path.Combine(_basePath, s);
p.Play();
}
}
}
}
The AT&T Text-To-Speech SDK is remarkable. You can do custom dictionaries and sounds. http://www.wizzardsoftware.com/text-to-speech-tts.php
Sound player should work:
using System.Media;
InitializeComponent();
Soundplayer MySounds = new SoundPlayer(#"C:\example.wav);
MySounds.Play();

Categories

Resources