write objects from array to text file c# [duplicate] - c#

This question already has answers here:
StreamWriter.Write doesn't write to file; no exception thrown
(8 answers)
Closed 4 years ago.
This C# assignment is about creating groups for salesmen at diffrent levels depending how much they sold for, and then write this info to a textfile using a streamwriter.
I have done all parts except the streamwriter part. What i do so far is to create the file, but there is no ouput.
When i run this the content in the console is correct but the textfile becomes modified but blank.
The streamwriter is in the bottom part.
´
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Inlämningsuppgift2
{
// Emplooyeklassen where names, personal info, district och sold items sparas och hämtas
class Emplooye
{
String namn;
int personnummer;
string distrikt;
int såldaartiklar;
int säljnivå;
public Emplooye(string namn, int personnummer, string distrikt, int såldaartiklar)
{
this.namn = namn;
this.personnummer = personnummer;
this.distrikt = distrikt;
this.såldaartiklar = såldaartiklar;
}
public string Name
{
get { return namn; }
set { namn = value; }
}
public int PersonNummer
{
get { return personnummer; }
set { personnummer = value; }
}
public string Distrikt
{
get { return distrikt; }
set { distrikt = value; }
}
public int AmountSold
{
get { return såldaartiklar; }
set { såldaartiklar = value; }
}
public int SäljNivå
{
get { return säljnivå; }
set { säljnivå = value; }
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Inlämningsuppgift2;
using System.IO;
namespace ConsoleApp3
{
class Säljlista
{
static void Main(string[] args)
{
List<Emplooye> ObjSeller = new List<Emplooye>();
List<Emplooye> group1 = new List<Emplooye>();
List<Emplooye> group2 = new List<Emplooye>();
List<Emplooye> group3 = new List<Emplooye>();
ObjSeller.Add(new Emplooye("Oscar Norberg", 961111, "Täby", 140));
ObjSeller.Add(new Emplooye("jonas okembia", 970912, "Uppsala", 70));
ObjSeller.Add(new Emplooye("Mille vega", 981212, "Danderyd", 40));
ObjSeller.Add(new Emplooye("Isak friisjespesen", 991132, "Skåne", 80));
ObjSeller.Add(new Emplooye("Maja olofsson", 974132, "Täby", 123));
ObjSeller.Add(new Emplooye("Annmarie norberg", 944432, "Täby", 230));
ObjSeller.Add(new Emplooye("Ulla persson", 9312332, "Uppland", 124));
ObjSeller.Add(new Emplooye("Christer Nilsen", 9988332, "Vallentuna", 444));
Console.WriteLine("Namn Personnummer Distrikt Antal");
//Here the employees gets sorted in groups depending how much they sold for.
foreach (Emplooye e in ObjSeller)
{
if (e.AmountSold > 0 && e.AmountSold <= 90)
{
group1.Add(e);
}
else if (e.AmountSold > 90 && e.AmountSold <= 200)
{
group2.Add(e);
}
else
{
group3.Add(e);
}
}
group1.Sort(delegate (Emplooye t1, Emplooye t2)
{ return (t1.AmountSold.CompareTo(t2.AmountSold)); }
);
for (int i = 0; i < group1.Count; i++)
{
string name = group1.ElementAt(i).Name;
int pnr = group1.ElementAt(i).PersonNummer;
String district = group1.ElementAt(i).Distrikt;
int amountsold = group1.ElementAt(i).AmountSold;
Console.WriteLine(name + ": " + pnr + " - " + district + " - " + amountsold);
}
Console.WriteLine("salesmen at level 1" + ": " + group1.Count);
Console.WriteLine("");
group2.Sort(delegate (Emplooye t1, Emplooye t2)
{ return (t1.AmountSold.CompareTo(t2.AmountSold)); }
);
for (int i = 0; i < group2.Count; i++)
{
string name = group2.ElementAt(i).Name;
int pnr = group2.ElementAt(i).PersonNummer;
String district = group2.ElementAt(i).Distrikt;
int amountsold = group2.ElementAt(i).AmountSold;
Console.WriteLine(name + ": " + pnr + " - " + district + " - " + amountsold);
}
Console.WriteLine("salesmen at level 2 2" + ": " + group2.Count);
Console.WriteLine("");
group3.Sort(delegate (Emplooye t1, Emplooye t2)
{ return (t1.AmountSold.CompareTo(t2.AmountSold)); }
);
for (int i = 0; i < group3.Count; i++)
{
string name = group3.ElementAt(i).Name;
int pnr = group3.ElementAt(i).PersonNummer;
String district = group3.ElementAt(i).Distrikt;
int amountsold = group3.ElementAt(i).AmountSold;
Console.WriteLine(name + ": " + pnr + " - " + district + " - " + amountsold);
}
Console.WriteLine("salesmen at level 3" + ": " + group3.Count);
Console.WriteLine("");
StreamWriter SW = new StreamWriter("important.txt");
foreach(Emplooye i in group1)
{
SW.WriteLine(group1.ToString());
foreach(Emplooye i in group2)
{
SW.WriteLine(group2.ToString());
}
foreach(Emplooye i in group3)
{
SW.WriteLine(group3.ToString());
}
}
}

You aren't closing the stream writer so it is buffering the output in memory but not writing to the file. Try a 'using' statement:
using(StreamWriter SW = new StreamWriter("important.txt"))
{
foreach(Emplooye i in group1)
{
SW.WriteLine(i.ToString());
}
foreach(Emplooye i in group2)
{
SW.WriteLine(i.ToString());
}
foreach(Emplooye i in group3)
{
SW.WriteLine(i.ToString());
}
}

Related

Strange unity bug in IOS

I am suffering from a strange bug in my project. It runs in unity perfectly but when I build it for IOS, it does one thing in particular differently. When a user picks up 8 items, I have an input box display these items and what order they selected them in. This works perfectly in unity but doesn't in IOS. Anyone have any suggestions as to why this might be the case. Below are the two appropriate scripts.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.IO;
public class PickUpItem : MonoBehaviour, IInteractable
{
//Go back to older version of clavem, find out what broke.
public string DisplaySprite;
public string DisplayImage;
public static string ItemChoosenOrder;
public static int counter;
public static GameObject InventorySlots;
public static GameObject[] PlayerItems = new GameObject[8];
public void Interact(DisplayImage currentDisplay)
{
ItemPickUp();
}
void Start()
{
PlayerItems = GameObject.FindGameObjectsWithTag("ChoosenItem");
}
void Update()
{
}
public void ItemPickUp()
{
InventorySlots = GameObject.Find("Slots");
counter = 0;
foreach (Transform slot in InventorySlots.transform)
{
if (slot.transform.GetChild(0).GetComponent<Image>().sprite.name == "empty_item")
{
slot.transform.GetChild(0).GetComponent<Image>().sprite =
Resources.Load<Sprite>("Inventory Items/" + DisplaySprite);
Destroy(gameObject);
break;
}
if (counter <= 7)
{
counter++;
if (counter >= 7)
{
{
Debug.Log("You have choosen all your items.");
foreach (Transform finalslot in InventorySlots.transform)
{
if (finalslot.transform.GetChild(0).GetComponent<Image>().sprite.name == "empty_item")
{
finalslot.transform.GetChild(0).GetComponent<Image>().sprite =
Resources.Load<Sprite>("Inventory Items/" + DisplaySprite);
Destroy(gameObject);
break;
}
}
//https://hub.packtpub.com/arrays-lists-dictionaries-unity-3d-game-development/
if (PlayerItems[7].GetComponent<Image>().sprite.name != "empty_item")
{
PlayerItems = GameObject.FindGameObjectsWithTag("ChoosenItem");
ItemChoosenOrder = "1: " + PlayerItems[0].GetComponent<Image>().sprite.name + " 2: " + PlayerItems[1].GetComponent<Image>().sprite.name
+ " 3: " + PlayerItems[2].GetComponent<Image>().sprite.name + " 4: " + PlayerItems[3].GetComponent<Image>().sprite.name
+ " 5: " + PlayerItems[4].GetComponent<Image>().sprite.name + " 6: " + PlayerItems[5].GetComponent<Image>().sprite.name
+ " 7: " + PlayerItems[6].GetComponent<Image>().sprite.name + " 8: " + PlayerItems[7].GetComponent<Image>().sprite.name;
Debug.Log(ItemChoosenOrder);
Debug.Log(counter);
}
else
{
Debug.Log("Error choosing items");
}
}
}
}
}
}
}
saveitemhash
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class SaveItemHash : MonoBehaviour
{
public InputField choosenitems;
public Text playerDisplay;
public Text InfoText;
public Button SaveButton;
private void Awake()
{
if (DBManager.email == null)
{
UnityEngine.SceneManagement.SceneManager.LoadScene(0);
}
playerDisplay.text = "User: " + DBManager.email;
}
public void CallAddItems()
{
StartCoroutine(AddChoosenItems());
}
IEnumerator AddChoosenItems()
{
//Using a unity web request to send email and choosen items string to my php scripts which echo a number depending on whether the user is successful or not.
WWWForm form = new WWWForm();
form.AddField("email", DBManager.email);
form.AddField("items", choosenitems.text);
WWW www = new WWW("https://clavem.000webhostapp.com/userregister.php", form);
yield return www;
if (www.text[0] == '0')
{
Debug.Log("User added successfully.");
UnityEngine.SceneManagement.SceneManager.LoadScene(0);
PickUpItem.counter = 0;
PickUpItem.ItemChoosenOrder = " ";
}
else
{
Debug.Log("User adding failed. Error #" + www.text);
InfoText.text = www.text;
PickUpItem.counter = 0;
PickUpItem.ItemChoosenOrder = " ";
}
}
public void Update()
{
playerDisplay.text = "User: " + DBManager.email;
if (PickUpItem.counter > 7)
{
//Do this for add field in last scene where the passwords are.
GameObject.Find("SaveButton").transform.localScale = new Vector3(1, 1, 1);
choosenitems.text = PickUpItem.ItemChoosenOrder;
GameObject.Find("InputField").transform.localScale = new Vector3(1, 1, 1);
//choosenitems.text = PickUpItem.ItemChoosenOrder;
//Debug.Log(PickUpItem.ItemChoosenOrder);
}
if (PickUpItem.counter < 7)
{
GameObject.Find("SaveButton").transform.localScale = new Vector3(0, 0, 0);
GameObject.Find("InputField").transform.localScale = new Vector3(0, 0, 0);
}
}
public void RestartScene()
{
UnityEngine.SceneManagement.SceneManager.LoadScene(3); ;
PickUpItem.counter = 0;
PickUpItem.ItemChoosenOrder = " ";
}
}
Working answer using a List collection and directly linking the order by adding each item to the array corresponding to each inventory slot in the appropriate order.
PickUpItem Script
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.IO;
using System.Linq;
public class PickUpItem : MonoBehaviour, IInteractable
{
public string DisplaySprite;
public string DisplayImage;
public static List<string> itemOrder = new List<string>();
public static string ItemChoosenOrder;
public static int counter;
public static GameObject InventorySlots;
public static GameObject[] PlayerItems = new GameObject[8];
public void Interact(DisplayImage currentDisplay)
{
ItemPickUp();
}
void Start()
{
PlayerItems = GameObject.FindGameObjectsWithTag("ChoosenItem");
}
void Update()
{
}
public void ItemPickUp()
{
InventorySlots = GameObject.Find("Slots");
counter = 0;
int j;
foreach (Transform slot in InventorySlots.transform)
{
if (slot.transform.GetChild(0).GetComponent<Image>().sprite.name == "empty_item")
{
slot.transform.GetChild(0).GetComponent<Image>().sprite =
Resources.Load<Sprite>("Inventory Items/" + DisplaySprite);
Destroy(gameObject);
break;
}
if (counter <= 7)
{
//itemOrder.Add(PlayerItems[counter].GetComponent<Image>().sprite.name);
counter++;
if (counter >= 7)
{
{
PlayerItems = GameObject.FindGameObjectsWithTag("ChoosenItem");
Debug.Log("You have choosen all your items.");
foreach (Transform finalslot in InventorySlots.transform)
{
if (finalslot.transform.GetChild(0).GetComponent<Image>().sprite.name == "empty_item")
{
finalslot.transform.GetChild(0).GetComponent<Image>().sprite =
Resources.Load<Sprite>("Inventory Items/" + DisplaySprite);
Destroy(gameObject);
break;
}
}
itemOrder.Add(GameObject.Find("item0").GetComponent<Image>().sprite.name);
itemOrder.Add(GameObject.Find("item1").GetComponent<Image>().sprite.name);
itemOrder.Add(GameObject.Find("item2").GetComponent<Image>().sprite.name);
itemOrder.Add(GameObject.Find("item3").GetComponent<Image>().sprite.name);
itemOrder.Add(GameObject.Find("item4").GetComponent<Image>().sprite.name);
itemOrder.Add(GameObject.Find("item5").GetComponent<Image>().sprite.name);
itemOrder.Add(GameObject.Find("item6").GetComponent<Image>().sprite.name);
itemOrder.Add(GameObject.Find("item7").GetComponent<Image>().sprite.name);
//https://hub.packtpub.com/arrays-lists-dictionaries-unity-3d-game-development/
if (PlayerItems[7].GetComponent<Image>().sprite.name != "empty_item")
{
PlayerItems = GameObject.FindGameObjectsWithTag("ChoosenItem");
for (j = 0; j < 8; j++)
{
Debug.LogFormat("Item[{0}] = {1}", j, itemOrder[j]);
}
ItemChoosenOrder = "1: " + itemOrder[0] + " 2: " + itemOrder[1]
+ " 3: " + itemOrder[2] + " 4: " + itemOrder[3]
+ " 5: " + itemOrder[4] + " 6: " + itemOrder[5]
+ " 7: " + itemOrder[6] + " 8: " + itemOrder[7];
Debug.Log(ItemChoosenOrder);
}
else
{
Debug.Log("Error choosing items");
}
}
}
}
}
}
}

C# Loop over all possible values, when not found increase value and continue

I need to send a request for every supplier code to a webservice (i know that sounds crazy but the owner designed it this way).
The supplier code format is:
30X1X1XXXXX1
You can check what i did so far (github link: https://github.com/rareba/SiapWebServices_Library/blob/master/SiapWebServices_Library/SiapWebServicesFornitore.cs)
public static List<StructAnaFornitoreOut> Get_All_Suppliers(WebServicesFornitoreClient client, StructLogin loginCredentials, string showSuspended = "N", string searchType = "R")
{
var supplier_list = new List<StructAnaFornitoreOut>();
var supplier_retrived = new StructAnaFornitoreOut
{
esito = new StructEsito
{
stato = "OK",
}
};
int KO_Count = 0;
int conto = 1;
int sottoconto = 1;
int codice = 0;
string codFornitore = Generate_Supplier_Code_String(codice, sottoconto, conto);
var search = new StructAnaFornitoreIn
{
IAnaFornitore = new StructAnaFornitore
{
codice = codFornitore
},
IAzione = "C",
//vModRicerca = new string[] { "COD_FIS","PAR_IVA","ALT_SIS" }
};
while (KO_Count < 10)
{
while (KO_Count < 10)
{
while (KO_Count < 10)
{
supplier_retrived = client.gestioneAnagraficaFornitore(loginCredentials, search);
if (supplier_retrived.esito.stato == "KO")
{
KO_Count++;
}
else
{
supplier_list.Add(supplier_retrived);
codFornitore = Generate_Supplier_Code_String(codice, sottoconto, conto);
Console.WriteLine(codFornitore);
codice++;
search.IAnaFornitore.codice = codFornitore;
}
}
KO_Count = 0;
sottoconto++;
}
KO_Count = 0;
conto++;
}
return supplier_list;
}
// Returns a supplier code string increased by 1
public static string Generate_Supplier_Code_String(int codice = 0, int sottoconto = 1, int conto = 1, string mastro = "30")
{
codice++;
string string_conto = " ";
string string_sottoconto = " ";
string string_codice = " ";
if (conto > 9)
{
string_conto = "";
}
if (sottoconto > 9)
{
string_sottoconto = "";
}
if (codice > 9)
{
string_codice = " ";
}
else if (codice > 99)
{
string_codice = " ";
}
else if (codice > 999)
{
string_codice = " ";
}
else if (codice > 9999)
{
string_codice = " ";
}
else if (codice > 99999)
{
string_codice = " ";
}
else if (codice >= 999999)
{
string_codice = "";
}
string customercode = mastro + string_conto + conto + string_sottoconto + sottoconto + string_codice + codice;
return customercode;
}
However this doesn't work at all: it stops at supplier 30 1 1 100 and starts increasing sottoconto like there is no tomorrow.
The idea should be to do something like:
- Get the supplier data
- Increase codice by 1
- If for 10 times you get nothing (esito.status = "KO") then increase sottoconto and start again from codice = 1
- If after incresing sottoconto you still get nothing for 10 times then increase conto and start again from codice = 0

Getting rank for baby name popularity ranking program

I'm trying to get this program finished but keep running into issues, I can't figure out how to get the count for ranking for the result I keep getting 1 for my output and I'm trying to get this finished as soon as I can. The output should look something like this :
Enter the directory path of the data files: C:\Intel
Enter the year:2010
Enter the gender (M/F): M
Enter the name: Javier
Javier is ranked #190 in year 2010
namespace QuestionTwo
{
class Program
{
static void Main(string[] args)
{
List<string> names = new List<string>();
Console.Write("Enter the directory path of the data files: ");
string filename = Console.ReadLine();
filename.Replace(#"\", #"\\");
Console.Write("Enter the year: ");
string year = Console.ReadLine();
Console.Write("Enter the gender (M/F): ");
string gender = Console.ReadLine();
Console.Write("Enter the name: ");
string name = Console.ReadLine();
filename += "\\yob" + year + ".txt";
string line = "";
try
{
using (StreamReader fin = new StreamReader(filename))
{
while((line = fin.ReadLine()) != null)
{
string[] parsed = line.Split(',');
if (parsed[1] == gender)
{
names.Add(parsed[0]);
}
}
}
for (int i = 0; i < names.Count; i++)
{
if (names[i] == (name))
{
Console.WriteLine(name + " is ranked #" + i + " in year " + year);
}
else //if (names[i] != (name)) // it is a logic error somewhere here
{
Console.WriteLine("The name " + name
+ " is not ranked in year " + year);
}
}
}
catch(Exception e )
{
Console.WriteLine("The file at {0} could not be read."+ e, filename);
}
for(int c = 0; c < names.Count; c++)
{
Console.WriteLine((c + 1) + ". " + names[c]);
}
Console.ReadKey();
}
}
}
Your program outputs too much because you are printing "The name " + name
+ " is not ranked in year " + year" for each name that doesn't match.
You need to add a flag to record whether you found the name while looking through the list, something like this: note I have also added a break keyword - once you've found the name, there's no need to continue looking.
You also need to subtract 1 from i to the output as your list starts from 0 and I expect you don't want a zero-based rank?
class Program
{
static void Main(string[] args)
{
List<string> names = new List<string>();
string filename = #"c:\temp\baby.txt";
string year = "1997";
string gender = "F";
string name = "Margaret";
string line = "";
try
{
using (StreamReader fin = new StreamReader(filename))
{
while((line = fin.ReadLine()) != null)
{
string[] parsed = line.Split(',');
if (parsed[1] == gender)
{
names.Add(parsed[0]);
}
}
}
bool foundName = false;
for (int i = 0; i < names.Count; i++)
{
if (names[i] == (name))
{
Console.WriteLine(name + " is ranked #" + i-1 + " in year " + year);
foundName = true;
break;
}
}
if (!foundName)
{
Console.WriteLine("The name " + name
+ " is not ranked in year " + year);
}
}
catch(Exception e )
{
Console.WriteLine("The file at {0} could not be read."+ e, filename);
}
for(int c = 0; c < names.Count; c++)
{
Console.WriteLine((c + 1) + ". " + names[c]);
}
Console.ReadKey();
}
}
Output:
Margaret is ranked #4 in year 1997
The name Doris is not ranked in year 1997
Notes:
Your search is case-sensitive so "margaret" doesn't match
Your gender check is also case-sensitive so "f" doesn't find a match

The name does not exists in the current context [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I've received two files: Sumator.cs and Kalkulator.cs # Visual Studio 2012
I think you don't need to see those two, but I did put them here anyways, go down page and check my problem.
Sumator.cs code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sumator2
{
class Sumator
{
bool Status = false;
double Suma = 0;
public Kalkulator Kalk = new Kalkulator();
public Sumator()
{
}
public void ZmienStatus()
{
Status = !Status;
}
public string PokazStatus()
{
if (Status == true)
return " Sumator włączony";
else
return " Sumator wyłaczony";
}
public void PokazWynikS()
{
if (Status == true)
Suma += Kalk.Wynik;
Console.WriteLine("Wynik działania : " + Kalk.L1.ToString() + " " + Kalk.Dzialanie.ToString() + " " + Kalk.L2.ToString() + " = " + Kalk.Wynik.ToString() + PokazStatus() + " Suma= " + Suma.ToString());
}
public void Zeruj()
{
Suma = 0;
}
}
}
Kalkulator.cs code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sumator2
{
class Kalkulator
{
public double L1;
public double L2;
public double Wynik;
public String Dzialanie = "";
public Kalkulator()
{
}
void Oblicz()
{
switch (Dzialanie)
{
case "+":
Wynik = L1 + L2;
break;
case "-":
Wynik = L1 - L2;
break;
case "*":
Wynik = L1 * L2;
break;
case "/":
Wynik = L1 / L2;
break;
}
}
public void PodajDzialanie(double licz1, double licz2, string dz)
{
L1 = licz1;
L2 = licz2;
Dzialanie = dz;
Oblicz();
}
public void PokazWynik()
{
Console.WriteLine("Wynik działania : " + L1.ToString() + " " + Dzialanie.ToString() + " " + L2.ToString() + " = " + Wynik.ToString());
}
}
}
and I've written my main code for those two.
Program.cs code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sumator2
{
class Program
{
static void Main(string[] args)
{
Sumator s1 = new Sumator();
s1.ZmienStatus();
bool userNum = true;
while (userNum)
{
double userDouble;
string userString = Console.ReadLine();
if (userNum = double.TryParse(userString, out userDouble))
{
userDouble = Convert.ToDouble(userString);
userNum = false;
}
else
{
Console.WriteLine("Nie podano liczby!");
userNum = true;
}
}
s1.Kalk.PodajDzialanie(userDouble, 2, "*");
s1.PokazWynikS();
s1.Kalk.PokazWynik();
s1.Kalk.PodajDzialanie(userDouble, 2, "+");
s1.PokazWynikS();
s1.Kalk.PokazWynik();
Console.ReadKey();
}
}
}
Problem is that I wanted to use s1.Kalk.PodajDzialanie() function with those arguments:
s1.Kalk.PodajDzialanie(userDouble, 2, "*");
and I got error like:
The name 'userDouble' does not exists in the current context
I mean wt*? This function does work normally if I do like:
s1.Kalk.PodajDzialanie(2, 2, "*");
You're declaring userDouble inside your while loop. Once you leave that loop, it's out of scope. Move it to before the loop and you should be fine. So instead you have:
bool userNum = true;
double userDouble;
while (userNum)
{
string userString = Console.ReadLine();
// Jesli sa liczby to convertujemy
if (userNum = double.TryParse(userString, out userDouble))
{
userDouble = Convert.ToDouble(userString);
userNum = false;
}
else
{
Console.WriteLine("Nie podano liczby!");
userNum = true;
}
}
You're declaring userDouble in a scope that the function does not have access to.
Change your code to this:
static void Main(string[] args)
{
Sumator s1 = new Sumator();
double userDouble; //moved declaration out of while loop
s1.ZmienStatus();
// Sprawdzanie czy w stringu sa liczby
bool userNum = true;
while (userNum)
{
string userString = Console.ReadLine();
// Jesli sa liczby to convertujemy
if (userNum = double.TryParse(userString, out userDouble))
{
userDouble = Convert.ToDouble(userString);
userNum = false;
}
else
{
Console.WriteLine("Nie podano liczby!");
userNum = true;
}
}
s1.Kalk.PodajDzialanie(userDouble, 2, "*");
s1.PokazWynikS();
s1.Kalk.PokazWynik();
s1.Kalk.PodajDzialanie(userDouble, 2, "+");
s1.PokazWynikS();
s1.Kalk.PokazWynik();
Console.ReadKey();
}
Your variable double userDouble; is declared within the while loop, you need to move it outside. Or mvoe your s1.Kalk.PodajDzialanie(userDouble, 2, "*"); inside the while loop before it ends.
Your variable userDouble is declared inside a block and the call you are trying to do is outside of that block; hence, the variable is out of scope, and thus doesn't exist in the context of the call.
{
declaration;
work;
}
call; // doesn't work
But this does work:
declaration;
{
work;
}
call; // OK

C# function to convert text input of feet/inches/meters/centimeters/millimeters into numeric values

I'm writing a function to take shorthand values and convert them into a standardized numeric format. Is there any standard code out there that would do "best possible" conversion of arbitrary measurement text and turn it into numeric measurements if the text is valid?
I guess I'm looking for something like bool TryParseMeasurement(string s, out decimal d). Does anyone know of a function like this?
Here's an example of some of the input values I've seen:
Imperial
6 inches
6in
6”
4 feet 2 inches
4’2”
4 ‘ 2 “
3 feet
3’
3 ‘
3ft
3ft10in
3ft 13in (should convert to 4’1”)
Metricc
1m
1.2m
1.321m
1 meter
481mm
Here's some code we wrote in an app quite some time ago, where we were doing something similar. It's not the best, but you may be able to adapt, or get some sort of jumping off point.
public static class UnitConversion
{
public static string[] lstFootUnits = new string[] {"foots", "foot", "feets", "feet", "ft", "f", "\""};
public static string sFootUnit = "ft";
public static string[] lstInchUnits = new string[] { "inches", "inchs", "inch", "in", "i", "\'" };
public static string sInchUnit = "in";
public static string[] lstPoundUnits = new string[] { "pounds", "pound", "pnds", "pnd", "lbs", "lb", "l", "p" };
public static string sPoundUnit = "lbs";
public static string[] lstOunceUnits = new string[] { "ounces", "ounce", "ozs", "oz", "o" };
public static string sOunceUnit = "oz";
public static string[] lstCentimeterUnits = new string[] { "centimeters", "centimeter", "centimetres", "centimetre", "cms", "cm", "c"};
public static string sCentimeterUnit = "cm";
public static string[] lstKilogramUnits = new string[] { "kilograms", "kilogram", "kilos", "kilo", "kgs", "kg", "k" };
public static string sKilogramsUnit = "kgs";
/// <summary>
/// Attempt to convert between feet/inches and cm
/// </summary>
/// <param name="sHeight"></param>
/// <returns></returns>
public static string ConvertHeight(string sHeight)
{
if (!String.IsNullOrEmpty(sHeight))
{
sHeight = UnitConversion.CleanHeight(sHeight);
if (sHeight.Contains(UnitConversion.sFootUnit))
{
sHeight = sHeight.Replace(UnitConversion.sFootUnit, "|");
sHeight = sHeight.Replace(UnitConversion.sInchUnit, "|");
string[] sParts = sHeight.Split('|');
double? dFeet = null;
double? dInches = null;
double dFeetParsed;
double dInchesParsed;
if (sParts.Length >= 2 && double.TryParse(sParts[0].Trim(), out dFeetParsed))
{
dFeet = dFeetParsed;
}
if (sParts.Length >= 4 && double.TryParse(sParts[2].Trim(), out dInchesParsed))
{
dInches = dInchesParsed;
};
sHeight = UnitConversion.FtToCm(UnitConversion.CalculateFt(dFeet ?? 0, dInches ?? 0)).ToString() + " " + UnitConversion.sCentimeterUnit;
}
else if (sHeight.Contains(UnitConversion.sCentimeterUnit))
{
sHeight = sHeight.Replace(UnitConversion.sCentimeterUnit, "|");
string[] sParts = sHeight.Split('|');
double? dCentimeters = null;
double dCentimetersParsed;
if (sParts.Length >= 2 && double.TryParse(sParts[0].Trim(), out dCentimetersParsed))
{
dCentimeters = dCentimetersParsed;
}
int? iFeet;
int? iInches;
if (UnitConversion.CmToFt(dCentimeters, out iFeet, out iInches))
{
sHeight = (iFeet != null) ? iFeet.ToString() + " " + UnitConversion.sFootUnit : "";
sHeight += (iInches != null) ? " " + iInches.ToString() + " " + UnitConversion.sInchUnit : "";
sHeight = sHeight.Trim();
}
else
{
sHeight = "";
}
}
else
{
sHeight = "";
}
}
else
{
sHeight = "";
}
return sHeight;
}
/// <summary>
/// Attempt to convert between Kgs and Lbs
/// </summary>
/// <param name="sWeight"></param>
/// <returns></returns>
public static string ConvertWeight(string sWeight)
{
if (!String.IsNullOrEmpty(sWeight))
{
sWeight = UnitConversion.CleanWeight(sWeight);
if (sWeight.Contains(UnitConversion.sKilogramsUnit))
{
sWeight = sWeight.Replace(UnitConversion.sKilogramsUnit, "|");
string[] sParts = sWeight.Split('|');
double? dKilograms = null;
double dKilogramsParsed;
if (sParts.Length >= 2 && double.TryParse(sParts[0].Trim(), out dKilogramsParsed))
{
dKilograms = dKilogramsParsed;
}
sWeight = UnitConversion.KgToLbs(dKilograms).ToString("#.###") + " " + UnitConversion.sPoundUnit;
}
else if (sWeight.Contains(UnitConversion.sPoundUnit))
{
sWeight = sWeight.Replace(UnitConversion.sPoundUnit, "|");
string[] sParts = sWeight.Split('|');
double? dPounds = null;
double dPoundsParsed;
if (sParts.Length >= 2 && double.TryParse(sParts[0].Trim(), out dPoundsParsed))
{
dPounds = dPoundsParsed;
}
sWeight = UnitConversion.LbsToKg(dPounds).ToString("#.###") + " " + UnitConversion.sKilogramsUnit;
}
else
{
sWeight = "";
}
}
else
{
sWeight = "";
}
return sWeight;
}
public static double? CalculateFt(double dFt, double dInch)
{
double? dFeet = null;
if (dFt >= 0 && dInch >= 0 && dInch <= 12)
{
dFeet = dFt + (dInch / 12);
}
return dFeet;
}
public static double KgToLbs(double? dKg)
{
if (dKg == null)
{
return 0;
}
return dKg.Value * 2.20462262;
}
public static double LbsToKg(double? dLbs)
{
if (dLbs == null)
{
return 0;
}
return dLbs.Value / 2.20462262;
}
public static double FtToCm(double? dFt)
{
if (dFt == null)
{
return 0;
}
return dFt.Value * 30.48;
}
public static bool CmToFt(double? dCm, out int? iFt, out int? iInch)
{
if (dCm == null)
{
iFt = null;
iInch = null;
return false;
}
double dCalcFeet = dCm.Value / 30.48;
double dCalcInches = dCalcFeet - Math.Floor(dCalcFeet);
dCalcFeet = Math.Floor(dCalcFeet);
dCalcInches = dCalcInches * 12;
iFt = (int)dCalcFeet;
iInch = (int)dCalcInches;
return true;
}
private static string CleanUnit(string sOriginal, string[] lstReplaceUnits, string sReplaceWithUnit)
{
System.Text.StringBuilder sbPattern = new System.Text.StringBuilder();
foreach (string sReplace in lstReplaceUnits)
{
if (sbPattern.Length > 0)
{
sbPattern.Append("|");
}
sbPattern.Append(sReplace);
}
sbPattern.Insert(0,#"(^|\s)(");
sbPattern.Append(#")(\s|$)");
System.Text.RegularExpressions.Regex rReplace = new System.Text.RegularExpressions.Regex(sbPattern.ToString(), System.Text.RegularExpressions.RegexOptions.IgnoreCase);
sOriginal = rReplace.Replace(sOriginal, sReplaceWithUnit);
/*foreach (string sReplace in lstReplaceUnits)
{
sOriginal = sOriginal.Replace(sReplace, " " + sReplaceWithUnit);
}*/
return sOriginal;
}
private static bool StringHasNumbers(string sText)
{
System.Text.RegularExpressions.Regex rxNumbers = new System.Text.RegularExpressions.Regex("[0-9]+");
return rxNumbers.IsMatch(sText);
}
private static string ReduceSpaces(string sText)
{
while (sText.Contains(" "))
{
sText = sText.Replace(" ", " ");
}
return sText;
}
private static string SeperateNumbers(string sText)
{
bool bNumber = false;
if (!String.IsNullOrEmpty(sText))
{
for (int iChar = 0; iChar < sText.Length; iChar++)
{
bool bIsNumber = (sText[iChar] >= '0' && sText[iChar] <= '9') ||
(sText[iChar] == '.' && iChar < sText.Length - 1 && sText[iChar + 1] >= '0' && sText[iChar + 1] <= '9');
if (iChar > 0 && bIsNumber != bNumber)
{
sText = sText.Insert(iChar, " ");
iChar++;
}
bNumber = bIsNumber;
}
}
return sText;
}
public static string CleanHeight(string sHeight)
{
if (UnitConversion.StringHasNumbers(sHeight))
{
sHeight = SeperateNumbers(sHeight);
sHeight = CleanUnit(sHeight, UnitConversion.lstFootUnits, UnitConversion.sFootUnit);
sHeight = CleanUnit(sHeight, UnitConversion.lstInchUnits, UnitConversion.sInchUnit);
sHeight = CleanUnit(sHeight, UnitConversion.lstCentimeterUnits, UnitConversion.sCentimeterUnit);
sHeight = SeperateNumbers(sHeight);
sHeight = ReduceSpaces(sHeight);
}
else
{
sHeight = "";
}
return sHeight;
}
public static string CleanWeight(string sWeight)
{
if (UnitConversion.StringHasNumbers(sWeight))
{
sWeight = SeperateNumbers(sWeight);
sWeight = CleanUnit(sWeight, UnitConversion.lstOunceUnits, UnitConversion.sOunceUnit);
sWeight = CleanUnit(sWeight, UnitConversion.lstPoundUnits, UnitConversion.sPoundUnit);
sWeight = CleanUnit(sWeight, UnitConversion.lstKilogramUnits, UnitConversion.sKilogramsUnit);
sWeight = SeperateNumbers(sWeight);
sWeight = ReduceSpaces(sWeight);
}
else
{
sWeight = "";
}
return sWeight;
}
}
It should serve you well to build an extension method of string for this purpose. When you build an extension method you attach a new function call to an existing class. In this we are go to attach a method to the 'string' class that returns a double, as the number of millimeters in a given imperial value, PROVIDED that the value can be parsed based on the examples you provide.
using System;
using System.Text;
namespace SO_Console_test
{
static class ConversionStringExtensions
{
//this is going to be a simple example you can
//fancy it up a lot...
public static double ImperialToMetric(this string val)
{
/*
* With these inputst we want to total inches.
* to do this we want to standardize the feet designator to 'f'
* and remove the inch designator altogether.
6 inches
6in
6”
4 feet 2 inches
4’2”
4 ‘ 2 “
3 feet
3’
3 ‘
3ft
3ft10in
3ft 13in (should convert to 4’1”) ...no, should convert to 49 inches, then to metric.
*/
//make the input lower case and remove blanks:
val = val.ToLower().Replace(" ", string.Empty);
//make all of the 'normal' feet designators to "ft"
string S = val.Replace("\'", "f").Replace("feet", "f").Replace("ft", "f").Replace("foot", "f").Replace("‘", "f").Replace("’", "f");
//and remove any inch designator
S = S.Replace("\"", string.Empty).Replace("inches", string.Empty).Replace("inch", string.Empty).Replace("in", string.Empty).Replace("“", string.Empty).Replace("”", string.Empty);
//finally we have to be certain we have a number of feet, even if that number is zero
S = S.IndexOf('f') > 0 ? S : "0f" + S;
//now, any of the inputs above will have been converted to a string
//that looks like 4 feet 2 inches => 4f2
string[] values = S.Split('f');
int inches = 0;
//as long as this produces one or two values we are 'on track'
if (values.Length < 3)
{
for (int i = 0; i < values.Length; i++)
{
inches += values[i] != null && values[i] != string.Empty ? int.Parse(values[i]) * (i == 0 ? 12 : 1) : 0 ;
}
}
//now inches = total number of inches in the input string.
double result = inches * 25.4;
return result;
}
}
}
With that in place "ImperialToMetric()" becomes a method of any string, and can be invoked anywhere the extension containing class ConversionStringExtensions is referenced. You can use it like:
namespace SO_Console_test
{
class Program
{
static void Main(string[] args)
{
showConversion();
Console.ReadLine();
}
private static void showConversion()
{
//simple start:
Console.WriteLine("6ft 2\"".ImperialToMetric().ToString() + " mm");
//more robust:
var Imperials = new List<string>(){"6 inches",
"6in",
"6”",
"4 feet 2 inches",
"4’2”",
"4 ‘ 2 “",
"3 feet",
"3’",
"3 ‘",
"3ft",
"3ft10in",
"3ft 13in"};
foreach (string imperial in Imperials)
{
Console.WriteLine(imperial + " converted to " + imperial.ImperialToMetric() + " millimeters");
}
}
}
Obviously, at this point a call to "Fred".ImperialToMetric is not going to play nice. You will need to had error handling and perhaps some options to turn 1234 mm 1.234 km etc. but once you flush this out you have a method you can use where ever you choose.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication5
{
class Program
{
static void Main(string[] args)
{
double km,m,f,i,cm;
Console.WriteLine("The distance between karachi and lahore in (kilometer)km is=");
km = Convert.ToInt32(Console.ReadLine());
m = km * 1000;
Console.WriteLine("The distance between karachi and lahore in meter(m) is="+m);
f = km * 3280.84;
Console.WriteLine("The distance between karachi and lahore in feet(f) is="+f);
i = km * 39370.1;
Console.WriteLine("The distance between karachi and lahore in inches(i) is="+i);
cm = m * 100;
Console.WriteLine("The distance between karachi and lahore in centimeter(cm) is="+cm);
Console.ReadLine();
}
}
}
An extension for string I wrote only to find out that there is already a solution here :) The only thing left to do is to replace "feet", "ft", "’" to "'" and "inches", "inch", "in", "“", "\"" to "''".
using System;
namespace CustomExtensions
{
public static class StringExtension
{
const float mPerFeet = 30.48f / 100;
const float mPerInch = 2.54f / 100;
// input options:
// 5'
// 5'6''
// 18''
// 24''
// 5'6
// 5 ' 6 ''
// 5' 6''
// corner cases:
// '' will return 0
// 5''6'' will interpret as 5'6''
// 5'6' will interpret as 5'6''
// 6 will interpret as 6''
// 6''' will interpret as 6''
public static float MetersFromFeetInches(this string feetInches)
{
float feet = 0;
float inches = 0;
string[] separators = new string[] { "'", "''", " " };
string[] subs = feetInches.Split(separators, StringSplitOptions.RemoveEmptyEntries);
if (subs.Length == 1)
{
if (feetInches.Trim().EndsWith("''"))
{
float.TryParse(subs[0], out inches);
}
else if (!feetInches.Trim().EndsWith("''") && !feetInches.Trim().EndsWith("'"))
{
float.TryParse(subs[0], out inches);
}
else
{
float.TryParse(subs[0], out feet);
}
}
else if (subs.Length > 1)
{
float.TryParse(subs[0], out feet);
float.TryParse(subs[1], out inches);
}
return feet * mPerFeet + inches * mPerInch;
}
}
}

Categories

Resources