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
Related
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());
}
}
I cant seem to pull the custom field values of a transaction search using Web Services.
searchTransaction.savedSearchId = "2017";
SearchResult result = netsuite.search(searchTransaction);
if(result.status.isSuccess)
{
SearchRow[] searchRows = result.searchRowList;
if(searchRows != null && searchRows.Length >= 1)
{
for (int i = 0; i < searchRows.Length; i++)
{
TransactionSearchRow transactionRow = (TransactionSearchRow)searchRows[i];
var iid = transactionRow.basic.internalId[0].searchValue;
double amount = transactionRow.basic.amount[0].searchValue;
string custfild = transactionRow.basic.customFieldList[0].scriptId;
Console.WriteLine("\n Transaction ID: " + iid.internalId);
Console.WriteLine("\n Amount: " + amount.ToString());
Console.WriteLine("\n customfield: " + custfield.ToString());
}
}
}
I know that the field is being returned because I can see it in the xml response. And custfield.ToString() does return the internal ID of the custom field.
I just cant seem to get the actual value.
Figured it out, posting in case anyone else has the same question:
searchTransaction.savedSearchId = "2017";
SearchResult result = netsuite.search(searchTransaction);
if(result.status.isSuccess)
{
SearchRow[] searchRows = result.searchRowList;
if(searchRows != null && searchRows.Length >= 1)
{
for (int i = 0; i < searchRows.Length; i++)
{
TransactionSearchRow transactionRow = (TransactionSearchRow)searchRows[i];
var iid = transactionRow.basic.internalId[0].searchValue;
double amount = transactionRow.basic.amount[0].searchValue;
string custfild = transactionRow.basic.customFieldList[0].scriptId;
SearchColumnStringCustomField custfild = (SearchColumnStringCustomField)transactionRow.basic.customFieldList[0];
Console.WriteLine("\n Transaction ID: " + iid.internalId);
Console.WriteLine("\n Amount: " + amount.ToString());
Console.WriteLine("\n custfild: " + custfild.searchValue);
}
}
}
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 6 years ago.
Improve this question
well i'm doing a code in C#,
this code allows you to add items to your code, price, unit, etc. save them in an array, and a menu will display the aggregated items.
I have a problem because I do it this way and apparently my code don't work, could someone help me?.
King Regards.
I'm newest in this.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Market
{
public class Menu
{
public static int item { get; set; }
public static string[] product = new string[item];
public static string[] code = new string[item];
public static string[] price = new string[item];
public static string[] unit = new string[item];
public void showMenu()
{
Console.WriteLine("1.- Add new item");
Console.WriteLine("2.- Show items");
Console.WriteLine("3.- Exit");
//Menu
while (true)
{
string option = Console.ReadLine();
switch (option)
{
case "1":
addItem();
break;
case "2":
showItems();
break;
case "3":
System.Environment.Exit(-1);
Console.ReadKey();
break;
default:
Console.WriteLine("Select one valid option..");
break;
}
}
}
public static void addItem()
{
Console.WriteLine("\nAmount of items to add");
item = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Insert the items.");
for (int i = 0; i < item; i++)
{
Console.WriteLine("\nItem[" + i + "]: ");
Console.Write("Product[" + i + "]: ");
product[i] = Console.ReadLine();
Console.Write("Code[" + i + "]: ");
code[i] = Console.ReadLine();
Console.Write("Price[" + i + "]: ");
price[i] = Console.ReadLine();
Console.Write("Unit[" + i + "]: ");
unit[i] = Console.ReadLine();
}
}
public static void showItems()
{
Console.WriteLine("******* SHOW ITEMS *******");
Console.WriteLine("Product ------------- Code ------------- Price ------------- Unit");
for (int i = 0; i < item; i++)
{
Console.WriteLine(product[i] + " " + code[i] + " " + price[i] + " " + unit[i]);
}
}
}
}
There are few problems with the code.
Arrays that you created for product, code, etc are of zero size as item value is by default. Inserting any value to 0 sized array throws an exception.
Also you should be cautious on accessing the static fields in not static context.
.
I would suggest define a class with these properties and use the List to keep collection.
public class Product
{
public string Name {get;set;}
public string Code {get;set;}
public double Price {get;set;}
public int Unit {get;set;}
}
Now modify your additem to create products.
public static void addItem()
{
Console.WriteLine("\nAmount of items to add");
item = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Insert the items.");
for (int i = 0; i < item; i++)
{
var product = new Product();
Console.WriteLine("\nItem[" + i + "]: ");
Console.Write("Product[" + i + "]: ");
product.Name = Console.ReadLine();
Console.Write("Code[" + i + "]: ");
product.Code = Console.ReadLine();
Console.Write("Price[" + i + "]: ");
product.Price = double.Parse(Console.ReadLine()); //read as double value.
Console.Write("Unit[" + i + "]: ");
product.Unit = int.Parse(Console.ReadLine()); // Read as int value
products.Add(product); // products is global/class variable.
}
}
Check this Demo, it gives you an idea to proceed.
You are initializing yours arrays with a zero length. You arrays and item property are static that are initializing at application start. So when you change item field your arrays have already been initialized with default value of int, that is zero. You should initialize your arrays after setting the item property. And even after this you will not be able to add items to your arrays. Try to use List<> instead.
The issue is the static variable item is initialized to 0 when the class loads. Once you change it by reading in the user inputted value, you don't allocate properly sized arrays for your static variables. You can fix this by doing so after reading in the value:
public static void addItem()
{
Console.WriteLine("\nAmount of items to add");
item = Convert.ToInt32(Console.ReadLine());
// initialize static vars to correct size, now that we have #items
product = new string[item];
code = new string[item];
price = new string[item];
unit = new string[item];
Console.WriteLine("Insert the items.");
for (int i = 0; i < item; i++)
{
Console.WriteLine("\nItem[" + i + "]: ");
Console.Write("Product[" + i + "]: ");
product[i] = Console.ReadLine();
Console.Write("Code[" + i + "]: ");
code[i] = Console.ReadLine();
Console.Write("Price[" + i + "]: ");
price[i] = Console.ReadLine();
Console.Write("Unit[" + i + "]: ");
unit[i] = Console.ReadLine();
}
}
You can see the fixed code in action at https://dotnetfiddle.net/n5lWTQ !
Just to get you started... you instantiated your arrays in the field declaration with a size of item
public static int item { get; set; }
public static string[] product = new string[item];
public static string[] code = new string[item];
public static string[] price = new string[item];
public static string[] unit = new string[item];
The problem with this is that the moment you access the Menu class, these lines of code immediately gets executed. And since the default value of an int is 0, you will have your array sizes to be 0. Try applying breakpoints into those line and you'll see.
Now what you can do here is instantiate them once you have set the value of item. So you will have your code to be something like this...
public static int item { get; set; }
//just declare your arrays here
public string[] product;
public string[] code;
public string[] price;
public string[] unit;
public void addItem()
{
Console.WriteLine("\nAmount of items to add");
item = Convert.ToInt32(Console.ReadLine());
//instantiate your arrays here since item will have a value you have set it into.
product = new string[item];
code = new string[item];
price = new string[item];
unit = new string[item];
Console.WriteLine("Insert the items.");
You could try using a list of objects containing the required fields of your item. A generic list will allow you to dynamically add items to the list without having to set the size during initialization. This means you can add items (using option 1) as many times as you like without changing the arrays.
In addition to setting the arrays to zero size when you initialized your class (as other answers have suggested), it looked as if you were re-using your int item property each time you wanted to add new items to your lists. This means that the variable was changing so your ShowItems() method did not function correctly.
Here is a working example:
using System;
using System.Collections.Generic;
namespace Market
{
public class Menu
{
public struct Item
{
public string product;
public string code;
public string price;
public string unit;
}
public static List<Item> items = new List<Item>();
public static void showMenu()
{
//Menu
while (true)
{
Console.WriteLine("\n1.- Add new item");
Console.WriteLine("2.- Show items");
Console.WriteLine("3.- Exit");
string option = Console.ReadLine();
switch (option)
{
case "1":
addItem();
break;
case "2":
showItems();
break;
case "3":
System.Environment.Exit(-1);
Console.ReadKey();
break;
default:
Console.WriteLine("Select one valid option..");
break;
}
}
}
public static void addItem()
{
Console.WriteLine("\nAmount of items to add");
int numbItemsToAdd = Convert.ToInt32(Console.ReadLine()); // needs validation
Console.WriteLine("Insert the items.");
for (int i = 0; i < numbItemsToAdd; i++)
{
Item item = new Item();
Console.WriteLine("\nItem[" + (i + 1) +"]: ");
Console.Write("Product[" + (i + 1) +"]: ");
item.product = Console.ReadLine();
Console.Write("Code[" + (i + 1) + "]: ");
item.code = Console.ReadLine();
Console.Write("Price[" + (i + 1) + "]: ");
item.price = Console.ReadLine();
Console.Write("Unit[" + (i + 1) + "]: ");
item.unit = Console.ReadLine();
items.Add(item);
}
}
public static void showItems()
{
Console.WriteLine("******* SHOW ITEMS *******");
Console.WriteLine("Product ------------- Code ------------- Price ------------- Unit");
foreach(Item i in items)
{
Console.WriteLine(i.product + " " + i.code + " " + i.price + " " + i.unit);
}
}
public static void Main()
{
showMenu();
}
}
}
public class Menu
{
public static int item { get; set; }
public static List<string> product = new List<string>();
public static List<string> code = new List<string>();
public static List<string> price = new List<string>();
public static List<string> unit = new List<string>();
public void showMenu()
{
//Menu
while (true)
{
Console.WriteLine("\n1.- Add new item");
Console.WriteLine("2.- Show items");
Console.WriteLine("3.- Exit \n");
string option = Console.ReadLine();
switch (option)
{
case "1":
addItem();
break;
case "2":
showItems();
break;
case "3":
System.Environment.Exit(-1);
Console.ReadKey();
break;
default:
Console.WriteLine("Select one valid option..");
break;
}
}
}
public static void addItem()
{
Console.WriteLine("\nAmount of items to add");
item = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Insert the items.");
for (int i = 1; i <= item; i++)
{
Console.WriteLine("\nItem[" + i + "]: ");
Console.Write("Product[" + i + "]: ");
product.Add(Console.ReadLine());
Console.Write("Code[" + i + "]: ");
code.Add(Console.ReadLine());
Console.Write("Price[" + i + "]: ");
price.Add(Console.ReadLine());
Console.Write("Unit[" + i + "]: ");
unit.Add(Console.ReadLine());
}
}
public static void showItems()
{
Console.WriteLine("******* SHOW ITEMS *******");
Console.WriteLine("Product ------------- Code ------------- Price ------------- Unit");
for (int i = 0; i < item; i++)
{
Console.WriteLine(product[i] + " " + code[i] + " " + price[i] + " " + unit[i]);
}
}
}
I've been trying to do this and I keep getting 9:30 when it should be 2:30. I want the difference in time between 11:00pm and 1:30am. I'm trying to make a program to help me keep track of working hours, but when I try to subtract time, it's done wrong. Some values are right and some are very wrong.
I'll post my class cause the main is only GUI and calling methods from this class:
Go all the way down to a method called workedHours or calc1stPeriod, this were I do my time calculations. They both basically do the same, but in different places.
class timeManager
{ private DateTime dt2,
dt3,
dt4,
dt;
//gets time for the 1st in
public void getTimeIn(TextBox inTxt, Button outB, DateTimePicker dtp)
{
//this tries to put the hours parsed in the variables. If it's wrong, goes to catch
try
{
ArrayList timeSplitted = new ArrayList(); // holds time (text) splitted
string[] splitTime = inTxt.Text.ToUpper().Split(':');
// adds splitted time to arraylist if there's an M in any split that index by spaces. Input format: 8:00 pm
for (int i = 0; i < splitTime.Length; i++)
{
timeSplitted.Add(splitTime[i]);
if (splitTime[i].Contains("M"))
{
string[] splitAm = splitTime[i].Split(' ');
timeSplitted.Add(splitAm[0]);
timeSplitted.Add(splitAm[1]);
}
}
// delete cause it's a duplicate of the last 2 indexes
timeSplitted.RemoveAt(1);
//date well organized
string a = dtp.Value.Month.ToString() + "/" + dtp.Value.Day.ToString() + "/" + dtp.Value.Year.ToString() + " " + timeSplitted[0] + ":" + timeSplitted[1] + " " +
timeSplitted[2];
dt = Convert.ToDateTime(a);
outB.Enabled = true;
}
catch
{
MessageBox.Show("Invalid entry", "Error!");
inTxt.Focus();
}
}
//displays total worked hours
public void workedHours(TextBox totBx)
{
TimeSpan tota1,
tota2,
final;
tota1 = dt.Subtract(dt2);
tota2 = dt3.Subtract(dt4);
final = tota1.Add(tota2);
totBx.Text = ("Days:" + Math.Abs(final.Days) + " Time:" + Math.Abs(final.Hours) + ":" + Math.Abs(final.Minutes)).ToString();
}
//gets time for the 2nd in
public void getTimeIn2(TextBox inTxt2, Button outB2, Button calcB, DateTimePicker dtp)
{
try
{
ArrayList timeSplitted = new ArrayList();
string[] splitTime = inTxt2.Text.ToUpper().Split(':');
for (int i = 0; i < splitTime.Length; i++)
{
timeSplitted.Add(splitTime[i]);
if (splitTime[i].Contains("M"))
{
string[] splitAm = splitTime[i].Split(' ');
timeSplitted.Add(splitAm[0]);
timeSplitted.Add(splitAm[1]);
}
}
timeSplitted.RemoveAt(1);
string a = dtp.Value.Month.ToString() + "/" + dtp.Value.Day.ToString() + "/" + dtp.Value.Year.ToString() + " " + timeSplitted[0] + ":" + timeSplitted[1] + " " +
timeSplitted[2];
dt3 = Convert.ToDateTime(a);
outB2.Enabled = true;
calcB.Enabled = false;
}
catch
{
MessageBox.Show("Invalid entry", "Error!");
inTxt2.Focus();
}
}
//gets time for the 1st out
public void getTimeOut(TextBox outTxt, Button inB2, Button calcB, DateTimePicker dtp)
{
try
{
ArrayList timeSplitted = new ArrayList();
string[] splitTime = outTxt.Text.ToUpper().Split(':');
for (int i = 0; i < splitTime.Length; i++)
{
timeSplitted.Add(splitTime[i]);
if (splitTime[i].Contains("M"))
{
string[] splitAm = splitTime[i].Split(' ');
timeSplitted.Add(splitAm[0]);
timeSplitted.Add(splitAm[1]);
}
}
timeSplitted.RemoveAt(1);
string a = dtp.Value.Month.ToString() + "/" + dtp.Value.Day.ToString() + "/" + dtp.Value.Year.ToString() + " " + timeSplitted[0] + ":" + timeSplitted[1] + " " +
timeSplitted[2];
dt2 = Convert.ToDateTime(a);
inB2.Enabled = true;
calcB.Enabled = true;
}
catch
{
MessageBox.Show("Invalid entry", "Error!");
outTxt.Focus();
}
}
//gets time for the 2nd out
public void getTimeOut2(TextBox outTxt2, TextBox resuTxt, DateTimePicker dtp)
{
try
{
ArrayList timeSplitted = new ArrayList();
string[] splitTime = outTxt2.Text.ToUpper().Split(':');
for (int i = 0; i < splitTime.Length; i++)
{
timeSplitted.Add(splitTime[i]);
if (splitTime[i].Contains("M"))
{
string[] splitAm = splitTime[i].Split(' ');
timeSplitted.Add(splitAm[0]);
timeSplitted.Add(splitAm[1]);
}
}
timeSplitted.RemoveAt(1);
string a = dtp.Value.Month.ToString() + "/" + dtp.Value.Day.ToString() + "/" + dtp.Value.Year.ToString() + " " + timeSplitted[0] + ":" + timeSplitted[1] + " " +
timeSplitted[2];
dt4 = Convert.ToDateTime(a);
workedHours(resuTxt);
}
catch
{
MessageBox.Show("Invalid entry", "Error!");
outTxt2.Focus();
}
}
//reset everything to default values
public void reset(TextBox txt1, TextBox txt2, TextBox txt3, TextBox txt4, TextBox txt5, Button btn2, Button btn3, Button btn4)
{
txt1.Text = "";
txt2.Text = "";
txt3.Text = "";
txt4.Text = "";
txt5.Text = "";
btn2.Enabled = false;
btn3.Enabled = false;
btn4.Enabled = false;
}
//calculates hours on the 1st period
public void calc1stPeriod(TextBox resultTxt)
{
TimeSpan finalDt = dt - (dt2);
if (Math.Abs(finalDt.Days) >= 1)
{
int finalHours = Math.Abs(finalDt.Days) * 24;
resultTxt.Text = (Math.Abs(finalDt.Hours) + finalHours + ":" + Math.Abs(finalDt.Minutes)).ToString();
}
else if (finalDt.Hours > 12)
{
resultTxt.Text = (Math.Abs(finalDt.Hours - 12) + ":" + Math.Abs(finalDt.Minutes)).ToString();
}
else if (finalDt.Hours < 12)
{
resultTxt.Text = (Math.Abs(finalDt.Hours) + ":" + Math.Abs(finalDt.Minutes)).ToString();
}
}
}
Solution:
ArrayList timeSplitted = new ArrayList(); // holds time (text) splitted
string[] splitTime = inTxt.Text.ToUpper().Split(':');
// adds splitted time to arraylist if there's an M in any split that index by spaces. Input format: 8:00 pm
for (int i = 0; i < splitTime.Length; i++)
{
timeSplitted.Add(splitTime[i]);
if (splitTime[i].Contains("M"))
{
string[] splitAm = splitTime[i].Split(' ');
timeSplitted.Add(splitAm[0]);
timeSplitted.Add(splitAm[1]);
}
}
// delete cause it's a duplicate of the last 2 indexes
timeSplitted.RemoveAt(1);
//date well organized
string a = dtp.Value.Month.ToString() + "/" + dtp.Value.Day.ToString() + "/" + dtp.Value.Year.ToString() + " " + timeSplitted[0] + ":" + timeSplitted[1] + " " +
timeSplitted[2];
dt = Convert.ToDateTime(a);
dtp = DateTimePicker
Finally does what I need. Works with day and night shifts. Thanks to all who helped. I will up vote what helped me the most.
You can use Timespan:
var dt1 = new DateTime(2014, 1, 1, 10, 0, 0);
var dt2 = new DateTime(2014, 1, 1, 13, 0, 0);
var t1 = new TimeSpan(dt2.Ticks - dt1.Ticks);
Also you should think about that DateTime is pretty different from TimeSpan. So you should change your design a bit and do not measure work hours in DatTime.
EDIT: By the way, DateTime as in the name is point in time. But TimeSpan (again as in the name) is some time span, so you can use DateTime of start and end of some event, but length of this event should be measured in TimeSpan.
EDIT: To make TimeSapn correctly work when substracting 11 pm yesterday from 2 am Today, you should specify a Day in DateTime initializer.
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime tmnext = DateTime.ParseExact(nextdatestring, "yyyyMMdd_HH:mm:ss.fff", provider);
DateTime tmpresent = DateTime.ParseExact(previousdatestring, "yyyyMMdd_HH:mm:ss.fff", provider);
TimeSpan prevdur = tmnext - tmpresent;
Or as suggested by Ehsan Sajjad
TimeSpan prevdur = tmnext.Subtract(tmpresent);
I think this is the best work around to convert the string to datetime and get the difference in hours
Just see the code below:
DateTime dt1=new DateTime(2000,2,2,23,0,0);
DateTime dt2=new DateTime(2000,2,3,1,30,0);
TimeSpan ts = dt2.Subtract(dt1);
In this code if you have both date in same day you get 21:30 but if put the dt2 in the day after the difference is 2:30.
I think you need to check it in same day and the day after and then select the smallest value.
It's suppose to allow the user to choose a team from the ListBox, click a button and display the number of times that team has won the World Series by referring to a .txt file (called World Series).
I'm trying to take the selected item and check how many times that selected item appears in the World Series .txt file.
Any pointers?
private void compareList()
{
StreamReader champFile = File.OpenText("WorldSeries.txt");
List<string> champList = new List<string>();
string selectedTeam;
while (!champFile.EndOfStream)
{
champList.Add(champFile.ReadLine());
}
while (teamList.SelectedIndex != 0)
{
selectedTeam = teamList.SelectedItem.ToString();
}
if (selectedTeam = champList???)
{
MessageBox.Show("The " + selectedTeam + "has won the World Series " + champList.????.Count + "times! ")
}
else
{
MessageBox.Show("The " + selectedTeam + "has never won the World Series.")
}
}
You can use File.ReadLines and some LINQ
selectedTeam = teamList.SelectedItem.ToString();
var count = File.ReadLines("WorldSeries.txt")
.Count(x => x.Contains(selectedTeam));
if(count > 0)
{
MessageBox.Show("The " + selectedTeam + "has won the World Series " + count + "times! ")
}
if (teamList.SelectedIndex == -1)
{
MessageBox.Show("Please select an Item first!");
return;
}
string selectedTeam = teamList.SelectedItem.ToString();
var count = File.ReadAllLines("WorldSeries.txt").Where(line => line ==selectedTeam).Count();
//var count = champList.Where(l=>l==selectedTeam).Count();
if (count >0)
{
MessageBox.Show("The " + selectedTeam + "has won the World Series " + count + "times! ");
}
else
{
MessageBox.Show("The " + selectedTeam + "has never won the World Series.")
}
You can do it simply this way
Updated Code
if(teamList.SelectedIndex != 0 && champList.Contains(SelectedTeam))
{
MessageBox.Show("The " + selectedTeam + "has won the World Series " + champList.Where(w => w == SelectedItem).Count() + "times! ");
}
Place the champList in a dictionary and increment a counter if they already exist.
private void compareList()
{
StreamReader champFile = File.OpenText("WorldSeries.txt");
Dictionary<string, int> champList = new Dictionary<string, int>();
string selectedTeam;
string currentChamp;
while (!champFile.EndOfStream)
{
currentChamp = champFile.ReadLine();
if(champList.containsKey(currentChamp))
champList.get(currentChamp) += 1;
else
champList.Add(champFile.ReadLine(), 1);
}
while (teamList.SelectedIndex != 0)
{
selectedTeam = teamList.SelectedItem.ToString();
}
if (champList.hasKey(selectedTeam))
{
MessageBox.Show("The " + selectedTeam + "has won the World Series " + champList.get(selectedTeam) + "times! ")
}
else
{
MessageBox.Show("The " + selectedTeam + "has never won the World Series.")
}
}