Converting Distance using C# - c#

Program Problem: I am trying to convert from one type of distance to the next after the user inputs the data. The user must select from one list to convert to the other list in distance. For example, selecting inches in one list to convert to yards in another list.
My code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Distance_Converter
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void ConvertButton_click(object sender, EventArgs e)
{
//int Inches = 1;
//int Feet = 12;
//int Yards = 36;
int distance_to_convert;
string lengthOption1;
string lengthOption2;
int inches_feet;
int inches_yard;
lengthOption1 = FromListBox.SelectedItem.ToString();
lengthOption2 = ToListBox.SelectedItem.ToString();
distance_to_convert = int.Parse(distancetoconvertTextBox.Text);
if ((FromListBox.SelectedIndex) != -1 && (ToListBox.SelectedIndex) != -1)
{
switch (lengthOption1)
{
case "Inches":
if (lengthOption2 == "Inches")
{
//object distancetoconvert = null;
ConvertedDistanceTextBox = distance_to_convert.ToString();
}
else if (lengthOption2 == "Feet")
{
inches_feet = distance_to_convert / 12;
ConvertedDistanceTextBox = inches_feet.ToString();
}
else if (lengthOption2 == "Yards")
{
inches_yard = distance_to_convert / 36;
ConvertedDistanceTextBox = inches_yard.ToString();
}
break;
case "Feet":
if (lengthOption2 == "Inches")
{
int feet_inches = distance_to_convert * 12;
ConvertedDistanceTextBox = feet_inches.ToString();
}
else if (lengthOption2 == "Feet")
{
ConvertedDistanceTextBox = distance_to_convert.ToString(); ;
}
else if (lengthOption2 == "Yards")
{
int feet_yard = distance_to_convert / 3;
ConvertedDistanceTextBox = feet_yard.ToString();
}
break;
case "Yards":
if (lengthOption2 == "Inches")
{
int Yards_inches = distance_to_convert * 36;
ConvertedDistanceTextBox = Yards_inches.ToString();
}
else if (lengthOption2 == "Feet")
{
int Yards_feet = distance_to_convert * 3;
ConvertedDistanceTextBox = Yards_feet.ToString();
}
else if (lengthOption2 == "Yards")
{
ConvertedDistanceTextBox = distance_to_convert.ToString(); ;
}
break;
}
}
}
private void Exitbutton_click(object sender, EventArgs e)
{
this.Close();
}
}
}
My dilemma: The code looks correct in every sense. However, when I try to convert from int to string on multiple occasions the IDE gives me a red line. The code won't compile and creates build errors. I am thinking that I will have to create a separate class to convert from int to string.
The error states: "Error CS0029 Cannot implicitly convert type 'string' to 'System.Windows.Forms.TextBox' "
It appears on line - 42, 47, 52, or any line that begins with ConvertedDistanceTextBox = .
My apologies, I am new to coding and I am trying to learn. And I am relatively new to stackoverflow.

You should set your string values to the text property of your textbox
ConvertedDistanceTextBox.Text = inches_yard.ToString();

Related

I need to find all the peaks and valleys in a list of data points using c#

This is my entire program. I have been working on this project for a week now and I am simply stuck. I have managed to read the CSV file and put the information in two lists that I then converted into arrays. Now I don't HAVE to do it like this. It's just simply what I managed to write and work and make sense in my head. This is where I've managed to get to and where I'm stuck. All I need is to be able to parse out ALL the peaks, or maximums, and valleys, or minimums, from the data points, and display them. If I can get that to happen then I can finally be done with this program. Any help and suggestions, code, anything like that would greatly appreciate. Like I said if you have a better formula that I can plug in and use without hard-coding points (because there's over 2000 of them) and display the outcome in a listbox or something then that would make my day. Thank y, everyone,ne in advance
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApp6
{
public partial class Form1 : Form
{
double firstX, firstY, secondX, secondY, thirdX, thirdY, rw, cl = 0.0;
int count = 0;
string x = "";
string y = "";
byte MinMax = 0; //0 equals rising, 1 equals falling
double Max = new Array[];
//double Min = new Array[];
private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
using (var reader = new StreamReader(#"D:\data.csv"))
{
List<string> listA = new List<string>();
List<string> listB = new List<string>();
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(',');
listA.Add(values[0]);
listB.Add(values[1]);
string[] xPoints = listA.ToArray();
string[] yPoints = listB.ToArray();
while (yPoints.Last() != null)
{
if (Convert.ToDouble(yPoints.First()) == 0.0)
{
firstY = Convert.ToDouble(yPoints.First());
}
if (Convert.ToDouble(yPoints.First()) != 0.0 && secondY == 0.0)
{
secondY = Convert.ToDouble(yPoints.Last());
if (secondY > firstY)
{
MinMax = 0;
}
else
{
MinMax = 1;
}
}
if (secondY != 0.0 && thirdY == 0.0)
{
thirdY = Convert.ToDouble(yPoints.Last());
if (MinMax == 0 && thirdY > secondY)
{
firstY = secondY;
secondY = thirdY;
}
else
{
Max[count,0] = secondY;
}
}
}
listBox1.Items.Add(values[0]);
listBox2.Items.Add(values[1]);
}
}
}
}
}
This snippet will get valleys and peaks on an array of y values, ignoring [0]
public void GetValleysAndPeaks(double[] yValues, out List<int> peakIndexes, out List<int> valleyIndexes)
{
peakIndexes = new List<int>();
valleyIndexes = new List<int>();
bool directionUp = yValues[0] <= yValues[1];
for(int i = 1; i < yValues.Length - 1; i++)
{
if(directionUp && yValues[i + 1] < yValues[i])
{
peakIndexes.Add(i);
directionUp = false;
}
else if(!directionUp && yValues[i + 1] > yValues[i])
{
valleyIndexes.Add(i);
directionUp = true;
}
}
}

error CS0246: The type or namespace name `AForge' could not be found. Are you missing a using directive or an assembly reference?

I'm trying to make a n-Queens with Genetic Algorithm in Unity3D, but this error appears everytime...
code:
using UnityEngine;
using System;
using System.Collections;
using AForge.Genetic;
using AForge.Math;
namespace AlgoritmoGenetico
{
public class GA : MonoBehaviour {
int populationSizeBox;
int iterationsBox;
int nRainhasBox;
int crossoverRateBox;
int motacaoRateBox;
int paradaBox;
//int selecao;
private String log = "";
private int nRainhas = 14;
private int nPopulacao = 14;
private int nGeracoes = 8000;
private int nParada = 100;
private double crossoverRate = 0.75;
private double mutationRate = 0.01;
// Use this for initialization
void Start () {
Iniciar ();
}
// Update is called once per frame
void Update () {
}
public void Iniciar(){
configuraAlgoritimo();
int selecao = 0; // definimos para o metodo roleta
ISelectionMethod metodoDeSelecao = (selecao == 0) ? (ISelectionMethod)new RouletteWheelSelection() :
(selecao == 1) ? (ISelectionMethod)new EliteSelection() :
(ISelectionMethod)new RankSelection();
AvaliadorDeRainhas avaliador = new AvaliadorDeRainhas();
Population populacao = new Population(nPopulacao, new ShortArrayChromosome(nRainhas, nRainhas - 1), avaliador, metodoDeSelecao);
populacao.CrossoverRate = crossoverRate;
populacao.MutationRate = mutationRate;
int iteracao = 0;
int pararEm = nParada;
while (iteracao < nGeracoes)
{
populacao.RunEpoch();
if (nParada > 0 && iteracao == pararEm)
{
atualizaDadosPara(iteracao, populacao);
pararEm += nParada;
}
if (populacao.BestChromosome.Fitness == nRainhas)
break;
iteracao++;
}
atualizaDadosPara(iteracao,populacao);
}
private void atualizaDadosPara(int iteracao,Population populacao)
{
log = "Geração: " + iteracao +
"\n Método de Seleção : " + populacao.SelectionMethod +
"\n Avaliação Média: " + populacao.FitnessAvg +
"\n Melhor Avaliação : " + populacao.FitnessMax +
"\n Melhor indivíduo: " + populacao.BestChromosome.ToString();
print (log);
}
private void configuraAlgoritimo(){
try
{
nPopulacao = Math.Max(10, Math.Min(100, int.Parse(populationSizeBox)));
}
catch
{
nPopulacao = 8;
}
try
{
nGeracoes = Math.Max(0, int.Parse(iterationsBox));
}
catch
{
nGeracoes = 100;
}
try
{
nRainhas = Math.Max(4, int.Parse(nRainhasBox));
}
catch
{
nRainhas = 8;
}
try
{
crossoverRate = Math.Max(0.0, int.Parse(crossoverRateBox));
}
catch
{
crossoverRate = 0.75;
}
try
{
mutationRate = Math.Max(0.0, int.Parse(motacaoRateBox));
}
catch
{
mutationRate = 0.01;
}
try
{
nParada = Math.Max(0, int.Parse(paradaBox));
}
catch
{
nParada = 0;
}
}
}
}
I've recreated the problem that occured in your case.
You're missing AForge.dll file in your project's \Assets folder.
DLL you are looking for should be located in AForge.NET Framework-x.x.x-(libs only)\Release folder that you probably have downloaded zipped from AForge.NET site.
If you still struggle to find it, consider redownloading whole package from choosing [ Download Libraries Only ]:
http://www.aforgenet.com/framework/downloads.html
I've also fixed some issues you had there. You don't need to cast int value with int.Parse() if it is declared as int already.
Just do Math.Max(x, y) etc with functions you are using.
Also you are not using anything from AForge.Math namespace. If that was intentional, consider removing using AForge.Math; as it's unused.

C# BlackJack - same card dealt to player & cpu? [closed]

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 8 years ago.
Improve this question
i'm working on a little black jack game for no apparent reason, and I've run into an issue and i can't figure out where i'm going wrong, the only thing i can imagine is that the 'new card' method is being called twice, too quickly...
The problem is that it's giving the same card to both players :/
Here is my code
Thank you! :)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace BlackJack_Reworked
{
public partial class BlackJack : Form
{
public BlackJack()
{
InitializeComponent();
}
class myVars
{
public static int cardsDrawn = 0;
public static int playerX = 230;
public static int playerY = 160;
public static int cpuX = 230;
public static int cpuY = 60;
public static int playerCardValue = 0;
public static int cpuCardValue = 0;
}
private PictureBox[] card = new PictureBox[100];
private void makeCard(string pickedCard, int x)
{
card[myVars.cardsDrawn] = new PictureBox();
if (x == 0)
{
card[myVars.cardsDrawn].Location = new Point(myVars.playerX, myVars.playerY);
myVars.playerX += 15;
}
if (x == 1)
{
card[myVars.cardsDrawn].Location = new Point(myVars.cpuX, myVars.cpuY);
myVars.cpuX += 15;
}
card[myVars.cardsDrawn].Image = (Image)Properties.Resources.ResourceManager.GetObject(pickedCard);
card[myVars.cardsDrawn].Size = new Size(72, 96);
card[myVars.cardsDrawn].Parent = this;
card[myVars.cardsDrawn].BringToFront();
card[myVars.cardsDrawn].Update();
myVars.cardsDrawn++;
checkScores(false);
}
private void newCard(int x)
{
Random cardPicker = new Random();
int cardChoice = cardPicker.Next(1, 13);
int houseChoice = cardPicker.Next(1, 4);
string house = null;
switch (houseChoice)
{
case 1:
house = "Hearts";
break;
case 2:
house = "Diamonds";
break;
case 3:
house = "Spades";
break;
case 4:
house = "Clubs";
break;
}
if (x == 0)
{
makeCard(house + Convert.ToString(cardChoice), 0);
myVars.playerCardValue += cardChoice;
}
if (x == 1)
{
makeCard(house + Convert.ToString(cardChoice), 1);
myVars.cpuCardValue += cardChoice;
}
}
private bool feelingLucky()
{
Random Dice = new Random();
if (myVars.cpuCardValue >= 20) { return false; }
if (myVars.cpuCardValue <= 16) { return true; }
if (myVars.cpuCardValue >= 17 && myVars.cpuCardValue <= 18) if (Dice.Next(1, 5) == 1) { return true; }
if (myVars.cpuCardValue == 19) if (Dice.Next(1, 10) == 1) { return true; }
return false;
}
private void updateHandValues()
{
lblPlayerHand.Text = "Player: " + myVars.playerCardValue.ToString();
lblCPUhand.Text = "CPU: " + myVars.cpuCardValue.ToString();
}
private void checkScores(bool stand)
{
if (stand == true)
{
if (myVars.playerCardValue <= 21 && myVars.playerCardValue > myVars.cpuCardValue)
{
MessageBox.Show("Win!");
btnNewGame.Visible = true;
}
else if (myVars.cpuCardValue <= 21 && myVars.cpuCardValue > myVars.playerCardValue)
{
btnNewGame.Visible = true;
MessageBox.Show("Lose!");
}
}
else
{
if (myVars.playerCardValue > 21)
{
MessageBox.Show("Bust!");
btnNewGame.Visible = true;
}
if (myVars.cpuCardValue > 21)
{
MessageBox.Show("Win!");
btnNewGame.Visible = true;
}
}
}
private void newGame()
{
for(int x = 0; x < myVars.cardsDrawn; x++) { card[x].Dispose(); }
myVars.cpuCardValue = 0;
myVars.playerCardValue = 0;
myVars.cpuX = 230;
myVars.playerX = 230;
btnNewGame.Visible = false;
newCard(0); newCard(1);
}
private void btnNewGame_Click(object sender, EventArgs e)
{
newGame();
}
private void btnHit_Click(object sender, EventArgs e)
{
newCard(0); newCard(1);
updateHandValues();
}
private void btnStand_Click(object sender, EventArgs e)
{
if (feelingLucky() == true) newCard(1);
else checkScores(true);
}
}
}
EDIT Here's the code to my new and working version with help from these nice guys below, just in case someone finds it useful, thanks everyone!
Here are the card picture files you'll need to add to your project's resources for this code to work.
I know my logic probably isn't great, but i feel like I've learnt from this little project, hopefully someone else might too, now, time to conjure up something new.. thanks stackoverflow.
Playing Card Pictures Download
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Text.RegularExpressions;
namespace BlackJack_Reworked
{
public partial class BlackJack : Form
{
public BlackJack()
{
InitializeComponent();
}
private PictureBox[] Card = new PictureBox[52];
static List<string> Deck = new List<string>();
class myVars
{
public static int playerX = 230;
public static int cpuX = 230;
public static int playerCardValue = 0;
public static int cpuCardValue = 0;
public static int cardsDrawn = 0;
}
private void newDeck()
{
Deck.Clear();
for (int x = 0; x < myVars.cardsDrawn; x++)
{
Card[x].Dispose();
}
for (int x = 0; x < 52; x++)
{
int cardSuite = (x / 13) + 1;
int faceValue = (x % 13) + 1;
string Suite = null;
switch (cardSuite)
{
case 1:
Suite = "Hearts";
break;
case 2:
Suite = "Diamonds";
break;
case 3:
Suite = "Spades";
break;
case 4:
Suite = "Clubs";
break;
}
Deck.Add(Suite + Convert.ToString(faceValue));
}
Extensions.Shuffle(Deck);
myVars.cardsDrawn = myVars.cpuCardValue = myVars.playerCardValue = 0;
myVars.cpuX = myVars.playerX = 230;
}
private void handCard(string recipient)
{
Random Random = new Random(); Extensions.Shuffle(Deck);
string pickedCard = Deck[Random.Next(Deck.Count)];
int cardvalue = Convert.ToInt32(Regex.Replace(pickedCard, "[^0-9]", ""));
Card[myVars.cardsDrawn] = new PictureBox();
if (recipient == "player") {
Card[myVars.cardsDrawn].Location = new Point(myVars.playerX, 160); myVars.playerX += 15;
myVars.playerCardValue += cardvalue;
}
if (recipient == "cpu") {
Card[myVars.cardsDrawn].Location = new Point(myVars.cpuX, 60); myVars.cpuX += 15;
myVars.cpuCardValue += cardvalue;
}
Card[myVars.cardsDrawn].Image = (Image)Properties.Resources.ResourceManager.GetObject(pickedCard);
Card[myVars.cardsDrawn].Size = new Size(72, 96);
Card[myVars.cardsDrawn].Parent = this;
Card[myVars.cardsDrawn].BringToFront();
Card[myVars.cardsDrawn].Update();
Deck.Remove(pickedCard); myVars.cardsDrawn++; updateHandValues();
}
private void updateHandValues()
{
lblPlayerHand.Text = "Player: " + myVars.playerCardValue.ToString();
lblCPUhand.Text = "CPU: " + myVars.cpuCardValue.ToString();
}
private void newGame()
{
lblBlackJack.Text = "♠ Blackjack ♥";
btnNewGame.Visible = false;
newDeck(); handCard("player"); handCard("cpu");
}
private void checkCards()
{
if (playerWins() == true)
{
lblBlackJack.Text = "♠ You Win! ♥";
btnNewGame.Visible = true;
}
else if (playerWins() == false)
{
lblBlackJack.Text = "♠ Dealer Wins! ♥";
btnNewGame.Visible = true;
}
}
private void tieBreak()
{
if (myVars.cpuCardValue == myVars.playerCardValue && myVars.cpuCardValue >= 17)
{
lblBlackJack.Text = "♠ Tie! ♥";
btnNewGame.Visible = true;
}
else { checkCards(); }
}
private bool? playerWins()
{
if(myVars.cpuCardValue == 21 || myVars.playerCardValue > 21) { return false; }
if(myVars.playerCardValue == 21 || myVars.cpuCardValue > 21) { return true; }
else { return null; }
}
private bool cpuShouldPlay(bool stand)
{
Random Dice = new Random();
if (stand == false)
{
if (myVars.cpuCardValue <= 15) { return true; }
if (myVars.cpuCardValue >= 20 && myVars.cpuCardValue <= 21 && myVars.cpuCardValue > myVars.playerCardValue) { return false; }
if (myVars.cpuCardValue == 19 && myVars.cpuCardValue < myVars.playerCardValue) { return true; } else { return false; }
}
else
{
if(myVars.cpuCardValue < myVars.playerCardValue)
{
return true;
}
else { return false; }
}
}
private void btnNewGame_Click(object sender, EventArgs e)
{
newGame();
}
private void btnHit_Click(object sender, EventArgs e)
{
handCard("player"); if(cpuShouldPlay(false) == true) handCard("cpu"); checkCards();
}
private void btnStand_Click(object sender, EventArgs e)
{
if (cpuShouldPlay(true) == true) handCard("cpu"); tieBreak();
}
}
public static class Extensions
{
public static void Shuffle<T>(this IList<T> list)
{
Random rng = new Random();
int n = list.Count;
while (n > 1)
{
n--;
int k = rng.Next(n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
}
}
If you're playing from single deck rules, you must use a 'bag' or 'no replacement' model of random value source. Initially , fill the bag with all 52 possible cards. Then each iteration, pick one card at random from what remains in the bag, removing it from the bag. When the bag is empty, refill it.
Do note that when picking a random card from a bag that has n remaining items, your random value, being the index of the item in the bag to take, must be no larger than n-1 (assuming indicies run from 0 to n-1).
However, there are models of blackjack where multiple decks are shuffled together; many casinos play like this. From Wikipedia Blackjack, rules of play at casinos:
At a casino blackjack table, the dealer faces five to seven playing positions from behind a semicircular table. Between one and eight standard 52-card decks are shuffled together.
In this above model, it is certainly possible for the same card to be dealt twice in a row; however, depending on how many decks are shuffled together, this can happen only a limited number of times.
If I understand your code correctly, you currently model a blackjack shoe that has an infinite number of decks shuffled together.
Random.Next method generates random number from current time stamp and previously generated number (known as 'seed'). As you are create new object of Random everytime, it initializes with same seed. In your case, timestamp and seed doesn't change to 'Next' method of Random.
If you use single object of Random for all your operation, seed will change for each call of 'next'.
Second: You need to keep track of which cards are already drawn, so I've create a shoe list. I will remove the cards which are already used, just like real table.
NOTE: create a new shoe, when your number of cards are let's say 20.
List<string> aShoe = new List<string>(); //shoe contains 4 to 8 decks. Depending upon blackjack version.
int numberOfDeckPerShoe = 4;
private void CreateNewDeck()
{
for(int i =0;i <numberOfDeckPerShoe;i++)
for(int j=0;j<52;j++)
{
int cardFace = (j%13)+1;
int cardSuite = (j/13) + 1;
string Suite = null;
switch (cardSuite)
{
case 1:
Suite = "Hearts";
break;
case 2:
Suite = "Diamonds";
break;
case 3:
Suite = "Spades";
break;
case 4:
Suite = "Clubs";
break;
}
aShoe.add(Suite + Convert.ToString(cardFace));
}
}
Random cardPicker = new Random(); //This is change
private void newCard(int x)
{
int cardChoice = 0;
int houseChoice = 0;
string cardDrawn = "";
int cardToDraow = cardPicker.Next(0,aShoe.length);
cardDrawn = card aShoe[cardToDraow];
card.removeAt(cardToDraow);
if (x == 0)
{
makeCard(cardDrawn, 0);
myVars.playerCardValue += cardChoice;
}
if (x == 1)
{
makeCard(cardDrawn, 1);
myVars.cpuCardValue += cardChoice;
}
}
You are declaring a new Random() within the new card method.
If the method is being called twice, and very quickly, the seed's that are automatically generated (Based on time I believe) will be so close that they will generate pretty much the same number.
The best thing to do would be to create your instance of random outside of the method, and pass the random in each time, that way you will not get the same number each call.

Port Selection and Batch Runner Application

I have never written an application, so I will post the entirety of the code (80 lines). (I come from a background of putting together scripts.)
My goal is to load, or create a list of "used" ports, choose a number within a range that isn't on the list, and if the amount of tries to reach an unused port reaches 129, to run a windows batch file.
This also would turn the chosen port into a .cmd
(some of this is an amalgamation of sources from SO)
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Diagnostics;
using System.IO;
namespace randomport
{
class Core
{
public const int
minval = 8001,
maxval = 8128;
public static int[] usedPorts = new int[]{};
public static int
chosenPort = 0,
tries = 0,
timeout = 10;
public static bool read = false;
public static void Main()
{
if(!read)
{
Read();
read = true;
}
RandGen();
}
public static void RandGen()
{
Process proc = null;
Random rand = new Random();
if(tries < 129) chosenPort = rand.Next(minval, maxval);
else
{
proc.StartInfo.FileName = #"C:\Users\Administrator\Desktop\TerrariaServer\filebin\sendservfull.bat";
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.UseShellExecute = false;
proc.Start();
proc.WaitForExit
(
(timeout <= 0)
? int.MaxValue : timeout * 100 * 60
);
}
for(int i = 0; i < usedPorts.Length; i++)
{
if(chosenPort != usedPorts[i])
{
Write();
// Application.Exit();
}
else
{
tries += 1;
return;
}
}
}
public static void Read()
{
using (StreamReader sr = new StreamReader(#"C:\Users\Administrator\Desktop\TerrariaServer\filebin\activeports.txt"))
{
string[] values = sr.ReadToEnd().Split(';');
for(int i = 0; i < values.Length; i++)
{
int.TryParse(values[i], out usedPorts[i]);
}
}
}
public static void Write()
{
File.AppendAllText(#"C:\Users\Administrator\Desktop\TerrariaServer\filebin\activeports.txt", "set port="+chosenPort+";");
File.Move(#"C:\Users\Administrator\Desktop\TerrariaServer\filebin\activeports.txt", Path.ChangeExtension(#"C:\Users\Administrator\Desktop\TerrariaServer\filebin\activeports.txt", ".cmd"));
}
}
}
I have a little work to do on the final export (like removing ";").
The script compiles, but does not run as intended. Something is definitely wrong, but I am unaware of it. If it is something obvious, I guess that would be handy, otherwise if it is simply format and so on, I clearly need to do a little more studying.
Compiled using visual studio 2008 express this time, and cleaned it up. It was hard to tell which were the issues without a debugger, such as a missing parenthesis.
File writing, compiling, and crashing solved..
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Diagnostics;
using System.IO;
namespace randomport
{
class Core
{
public static int[] usedPorts = new int[] { };
public static int
minval = 8001,
maxval = 8129,
chosenPort = 0,
timeout = 10,
temp = 1024;
public static bool read = false;
public static void Main(string[] args)
{
string path = System.Environment.GetEnvironmentVariable("USERPROFILE");
if (!Directory.Exists(String.Concat(path, "\\desktop\\TerrariaServer\\filebin\\activeports.txt")))
{
Directory.CreateDirectory(String.Concat(path, "\\desktop\\TerrariaServer\\filebin"));
// using (StreamWriter sw = File.CreateText(String.Concat(path, "\\desktop\\TerrariaServer\\filebin\\activeports.txt"))) { }
}
if (!Directory.Exists(String.Concat(path, "\\desktop\\TerrariaServer\\filebin\\chosenport.cmd")))
{
Directory.CreateDirectory(String.Concat(path, "\\desktop\\TerrariaServer\\filebin"));
using (StreamWriter sw = File.CreateText(String.Concat(path, "\\desktop\\TerrariaServer\\filebin\\chosenport.cmd"))) { }
}
if (args.Length > 0)
{
if (args[0] == "-noread")
{
}
else if (args[0] == "-read" || args[0] == "-default")
{
if (!read)
{
Read();
read = true;
}
}
}
else
{
if (!read)
{
Read();
read = true;
}
}
if (args.Length >= 3)
{
if (args[1] != "-default" || args[1] != "0")
{
int.TryParse(args[1], out temp);
if (temp > 1024 && temp < 65535)
{
minval = temp;
}
}
if (args[2] != "-default" || args[2] != "0")
{
int.TryParse(args[2], out temp);
if (temp > 1024 && temp < 65535)
{
maxval = temp;
}
}
}
RandGen();
}
public static void RandGen()
{
string path = System.Environment.GetEnvironmentVariable("USERPROFILE");
Random rand = new Random();
chosenPort = rand.Next(minval, maxval);
for (int i = 0; i < usedPorts.Length; i++)
{
if (chosenPort != usedPorts[i])
{
Write();
}
else return;
}
}
public static void Read()
{
string path = System.Environment.GetEnvironmentVariable("USERPROFILE");
if (!File.Exists(String.Concat(path, "\\desktop\\TerrariaServer\\filebin\\activeports.txt")))
{
File.Create(String.Concat(path, "\\desktop\\TerrariaServer\\filebin\\activeports.txt"));
}
using (StreamReader sr = new StreamReader(String.Concat(path, "\\desktop\\TerrariaServer\\filebin\\activeports.txt")))
{
string[] values = sr.ReadToEnd().Split(';');
usedPorts = new int[values.Length];//Initialize the array with the same length as values
for (int i = 0; i < values.Length; i++)
{
int.TryParse(values[i], out usedPorts[i]);
}
}
}
public static void Write()
{
string path = System.Environment.GetEnvironmentVariable("USERPROFILE");
File.AppendAllLines(String.Concat(path, "\\desktop\\TerrariaServer\\filebin\\activeports.txt"), new string[] { chosenPort + ";" });
using (StreamWriter sw2 = File.CreateText(String.Concat(path, "\\desktop\\TerrariaServer\\filebin\\chosenport.cmd")))
{
sw2.WriteLine("set port=" + chosenPort);
}
Environment.Exit(0);
}
}
}

C# Calculation Program - Inputs Textboxes

When I hit the 'calculate' button, the 'additional programs' and 'installations' textboxes revert back to 0 and the 'bill' comes out to the base price for the given customer type. My code is below:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Bus432_Assignment2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnCalculate_Click(object sender, EventArgs e)
{
const double RES_HOME = 99;
const double RES_HOME_ADD = 49;
const double ENT_ADD_PRO = 10;
const double ENT_BASIC = 249;
const double ENT_PER_PRO = 99;
const double ENT_ADD_INSTALL_CHARGE = .10;
const double UNLIM_BASIC = 999;
char customerType;
double addpro = 0;
double install = 0;
double bill = 0;
// Check to make sure type has been entered.
if (txtCustomerType.Text == "")
{
MessageBox.Show("Customer type is required.",
Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
txtCustomerType.Focus();
return;
}
// Get customer type
customerType = char.Parse(txtCustomerType.Text);
customerType = char.ToUpper(customerType);
txtCustomerType.Text = customerType.ToString();
// Check customer type, programs, installations
txtInstall.Text = install.ToString();
txtAddPro.Text = addpro.ToString();
if (customerType == 'H' || customerType == 'E')
{
if (txtInstall.Text == "")
{
MessageBox.Show("For home use customer plan, enter installations",
Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
if (txtInstall.Text == "")
{
txtInstall.Focus();
}
return;
}
}
else if (customerType == 'E' || customerType == 'H')
{
if (txtAddPro.Text == "")
{
MessageBox.Show("For enterprise or home use customer, enter additional programs",
Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
if (txtAddPro.Text == "")
{
txtAddPro.Focus();
}
return;
}
else if (customerType != 'E' || customerType != 'H' || customerType != 'U')
{
MessageBox.Show("Customer type must be E, H, or U.",
Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
//txtInstall.Focus();
return;
}
// Get Additional Programs and installations
addpro = double.Parse(txtAddPro.Text);
install = double.Parse(txtInstall.Text);
if (addpro < 0)
{
MessageBox.Show("Number of additional programs must not be negative.",
Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
txtAddPro.Focus();
return;
}
else if (install < 0 )
{
MessageBox.Show("Number of installations must not be negative.",
Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
txtInstall.Focus();
return;
}
}
// Calculate Bill
switch(customerType)
{
case 'H':
bill = RES_HOME + addpro * RES_HOME_ADD;
break;
case 'E':
bill = ENT_BASIC + addpro * ENT_PER_PRO *(1+ENT_ADD_INSTALL_CHARGE*(install-ENT_ADD_PRO));
break;
case 'U':
bill = UNLIM_BASIC;
break;
}
// Display the result.
txtBill.Text = bill.ToString("C");
}
private void btnClose_Click(object sender, EventArgs e)
{
Close();
}
}
}
Within the code, you have declared these two variables
double addpro = 0;
double install = 0;
Then after you have declared these, you are setting the text of the boxes to equal them, without ever setting their values to anything but 0.
txtInstall.Text = install.ToString();
txtAddPro.Text = addpro.ToString();
I am not too sure on what you are trying to achieve, so I cannot suggest what you should have there instead, however that is the source of your problems regarding displaying 0 within the text fields.

Categories