Getting error "Use of unassigned local variable" in C# - c#

I'm quite new to programming so forgive me if this is a simple fix. I am consistently getting an error "Use of unassigned local variable" in regards to to my string variable "city". What's confusing me is that I also have a string variable called "centreName" which does not bring up the same error even though it is also not initialized.
The point of this program is to have users input data for the name of a Science Centre and the city it's located in. I have tried initializing the "city" variable to both string city = null and string city = "", but when I run the program, the output shows up blank as opposed to what the user entered. This is not the case with my "centreName" var.
I will include the coding for both classes I am using. Please disregard my methods as I have yet to tweak them to fit this program. They are older methods I used for something previous and the coding does not apply here.
This is the class in which I'm getting the error:
class ScienceCentreApp
{
static void Main(string[] args)
{
string centreName;
string city;
decimal ticketPrice = 0;
int visitorCnt;
string[] dArray = new String[5];
int[] adultVisitors = new int[5];
decimal[] totalRevenue = new decimal[5];
char enterMoreData = 'Y';
ScienceCentreVisitation scv;
do
{
visitorCnt = GetData(out centreName, city, ticketPrice, dArray, adultVisitors, totalRevenue);
scv = new ScienceCentreVisitation(centreName, city, ticketPrice, dArray, adultVisitors, totalRevenue);
Console.Clear();
Console.WriteLine(scv);
Console.Write("\n\n\n\nDo you want to enter more data - " +
"(Enter y or n)? ");
if (char.TryParse(Console.ReadLine(), out enterMoreData) == false)
Console.WriteLine("Invalid data entered - " +
"No recorded for your respones");
} while (enterMoreData == 'y' || enterMoreData == 'y');
Console.ReadKey();
}
public static int GetData(out string centreName, string city, decimal ticketPrice, string[] dArray, int[] adultVisitors, decimal[] totalRevenue)
{
int i,
loopCnt;
Console.Clear();
Console.Write("Name of Centre: ");
centreName = Console.ReadLine();
Console.Write("City: ");
city = Console.ReadLine();
Console.Write("Ticket Price: ");
string inValue = Console.ReadLine();
ticketPrice = Convert.ToDecimal(inValue);
Console.Write("How many records for {0}? ", centreName);
string inValue1 = Console.ReadLine();
if (int.TryParse(inValue1, out loopCnt) == false)
Console.WriteLine("Invalid data entered - " +
"0 recorded for number of records");
for (i = 0; i < loopCnt; i++)
{
Console.Write("\nDate (mm/dd/yyyy): ");
dArray[i] = Console.ReadLine();
if (dArray[i] == "")
{
Console.WriteLine("No date entered - " +
"Unknown recorded for visits");
dArray[i] = "Unknown";
}
Console.Write("Number of One-Day Adult Visitors: ");
inValue1 = Console.ReadLine();
if (int.TryParse(inValue1, out adultVisitors[i]) == false)
Console.WriteLine("Invalid data entered - " +
"0 recorded for adults visited");
}
return i;
}
}
}
This is the other class that the first is calling:
class ScienceCentreVisitation
{
private string centreName;
private string city;
private decimal ticketPrice;
private string[] visitDate;
private int[] adultVisitors;
private decimal[] totalRevenue;
//constructors
public ScienceCentreVisitation()
{
}
public ScienceCentreVisitation(string cent)
{
centreName = cent;
}
public ScienceCentreVisitation(string cent, string cit, decimal price, string[] date, int[] visit, decimal[] rev)
{
visitDate = new string[date.Length];
adultVisitors = new int[visit.Length];
totalRevenue = new decimal[rev.Length];
Array.Copy(date, 0, visitDate, 0, date.Length);
Array.Copy(visit, 0, adultVisitors, 0, adultVisitors.Length);
Array.Copy(rev, 0, totalRevenue, 0, rev.Length);
centreName = cent;
city = cit;
ticketPrice = price;
}
//properties
public string CentreName
{
get
{
return centreName;
}
set
{
centreName = value;
}
}
public string City
{
get
{
return city;
}
set
{
city = value;
}
}
public decimal TicketPrice
{
get
{
return ticketPrice;
}
set
{
ticketPrice = value;
}
}
public string[] VisitDate
{
get
{
return visitDate;
}
set
{
visitDate = value;
}
}
public int[] AdultVisitors
{
get
{
return adultVisitors;
}
set
{
adultVisitors = value;
}
}
public decimal[] TotalRevenue
{
get
{
return totalRevenue;
}
set
{
totalRevenue = value;
}
}
//methods
public decimal CalculateTotalRevenue()
{
decimal totalRev;
int cntOfValidEntries;
int total = 0;
foreach (int c in adultVisitors)
total += c;
cntOfValidEntries = TestForZeros();
totalRev = (decimal)total / cntOfValidEntries;
return totalRev;
}
public int TestForZeros()
{
int numberOfTrueVisits = 0;
foreach (int cnt in adultVisitors)
if (cnt != 0)
numberOfTrueVisits++;
return numberOfTrueVisits;
}
public int GetIndexOfLeastVisited()
{
int minVisIndex = 0;
for (int i = 1; i < adultVisitors.Length; i++)
if (adultVisitors[i] > adultVisitors[minVisIndex])
minVisIndex = i;
return minVisIndex;
}
public int GetLeastVisited()
{
return adultVisitors[GetIndexOfLeastVisited()];
}
public string GetDateWithLeastVisited()
{
return visitDate[GetIndexOfLeastVisited()];
}
public int GetIndexOfMostRevenue()
{
int maxRevIndex = 0;
for (int i = 1; i < totalRevenue.Length; i++)
if (totalRevenue[i] > totalRevenue[maxRevIndex])
maxRevIndex = i;
return maxRevIndex;
}
public decimal GetMostRevenue()
{
return totalRevenue[GetIndexOfMostRevenue()];
}
public string GetDateWithMostRevenue()
{
return visitDate[GetIndexOfMostRevenue()];
}
public override string ToString()
{
return "Name of Centre: " + centreName +
"\nCity: " + city +
"\nDate of Least One-Day Adult Visitors:\t\t" + GetDateWithLeastVisited() +
"\nNumber of Least One-Day Adult Visitors: \t\t" + GetLeastVisited() +
"\nDate of Most Total Revenue Collected:\t\t" + GetDateWithMostRevenue() +
"\nHighest Total Revenue Collected:\t\t" + GetMostRevenue();
}
}
}
Thanks in advance!

The difference between centreName and city is that centreName is used as an out parameter. That means you can call the method with an uninitialized variable because it is guaranteed that the variable will be assigned a value inside the method.
In your case, both centreName and city are assigned values in GetData, so you can safely replace string city with out string city.

centreName is declared as an out parameter (meaning it will retain the last value you assign to it inside the method when you leave the method's scope), so it is getting initialized by get data. The rest of your variables are not being set by the get data call, because they are not out parameters.
On that point, out parameters are generally considered bad practice in C# (I can't speak to other languages). Most they obscure the purpose of the method, and it is very easy to accidentally overwrite the value of one of the out parameters after the method is called (or mistakenly initialize it). Instead of using out parameters, create an object that wraps your data and return that instead of an int.

Related

How to return true or false with message inside the bool method for parallel array C#?

Note: I am learning to use the arrays.
The issue with my bool method for the parallel array is that I want to return true or false with a message for balance being empty (equal to 0.00 in double data type) or not (return false). I got the result after running this code:
The balance is not empty
False
The balance is not empty
False
The balance is not empty False
In short, once I run those codes then it will be looping or will not read whether the user's balance is empty or not because it doesn't check if it is zero or less than a zero. Instead, they simply ignore it and then return a false.
Here is my code:
// declaring three parallel arrays that store name, account number, and balance with data types
string [] customerName = new string [2];
int [] bankAccount = new int [2];
double [] balance = new double [2];
customerName = new string [] { "John Doe", "Jane Doe", "John Smith" };
bankAccount = new int [] { 123456 , 654321 , 987654 };
balance = new double [] {100.00, 200.00, 300.00};
for ( int i = 0; i < customerName.Length; i++)
{
Console.WriteLine(customerName[i] + "\t" + "Account Number: " + bankAccount[i] + "\t" + "Balance: $" + balance[i]);
}
// declared three different balances for the deposit method since context is necessary for local variables
double balance1 = balance[0];
double balance2 = balance[1];
double balance3 = balance[2];
Console.WriteLine(isEmpty(balance1));
Console.WriteLine(isEmpty(balance2));
Console.WriteLine(isEmpty(balance3));
bool isEmpty (double balance)
{
bool balance1 = balance == 0;
bool balance2 = balance == 0;
bool balance3 = balance == 0;
if (balance == 0)
{
return true;
}
else
{
Console.WriteLine("The balance is not empty");
}
return balance1 || balance2 || balance3;
}
// hardcoded values for three customers' balances to be updated
double deposit = 200.00;
double deposit1 = 300.00;
double deposit2 = 400.00;
// declared three different customers' names for return with string data type
string firstCustomer = "John Doe";
string secondCustomer = "Jane Doe";
string thirdCustomer = "John Smith";
Console.WriteLine(Deposit(firstCustomer, balance1, deposit));
Console.WriteLine(Deposit(secondCustomer, balance2, deposit1));
Console.WriteLine(Deposit(thirdCustomer, balance3, deposit2));
// string return that will return the three customers with updated balance after the deposit which is string
string Deposit (string customerName, double balance, double deposit)
{
double newBalance = balance + deposit;
return customerName + " deposited $" + deposit + " and the new balance is " + newBalance;
}
Therefore, I need to simply check and then return false or true after deciding if the balance is empty or not. There is no error but simply shows some repeating and ignoring any that is return false. Instead, they will always return true no matter what it is.
It seems to me, if you are calling IsEmpty with one double, you simply need this:
bool IsEmpty(double balance)
{
if (balance == 0)
{
return true;
}
else
{
Console.WriteLine("The balance is not empty");
return false;
}
}
If you are calling it with an array:
bool IsEmpty(params double[] balances)
{
if (balances.Any(b => b == 0))
{
return true;
}
else
{
Console.WriteLine("No balance is empty");
return false;
}
}
The params keyword allows you to pass the array as separate variables, like IsEmpty(balance1, balance2, balance3).
Please note that I changed the name of the method from isEmpty to IsEmpty to follow standard C# naming conventions.
You're also better off creating one array and using a custom type:
Account[] accounts = new Account[]
{
new Account() { Customer = "John Doe", Number = 123456, Balance = 100m, },
new Account() { Customer = "Jane Doe", Number = 654321, Balance = 200m, },
new Account() { Customer = "John Smith", Number = 987654, Balance = 300m, },
};
public class Account
{
public string Customer { get; set; }
public int Number { get; set; }
public decimal Balance { get; set; }
}

Check the value exists in List using C#

I have List as mentioned below. Now When I am going to add new string value into this list, My method GetNewCopiedValue has to check the new text value into the list lstNames.If the name does not exist in the list it should return the value as it is. If the new string value is exist already in the list, it has to return the string with respective index number as like EC(1).For example, If I am sending EC(1) again to the list, the method has to check the value in the list and It should return EC(3) since EC(1) is exist already in the list, the method has to check the similar values and it should return the value with next index number which is not there in the list.
Main()
{
List<string> lstNames=new List<string>{"Ecard","EC","EC(1)","EC(2)","NCard(1)"};
var copiedValue= GetNewCopiedValue(lstNames,EC(2));
Console.WriteLine("Copied Text is :"+copiedValue);
}
public static string GetNewCopiedValue(List<string> lstNames,string sourceLabel)
{
label = sourceLabel;
if (lstNames.Any(i => i.Equals(sourceLabel)))
{
var labelSubstring = sourceLabel.Substring(0, sourceLabel.Length - 2);
var sameNameList = lstNames.Where(i => i.Contains(labelSubstring)).ToList();
int count = sameNameList.Count+1;
label = labelSubstring + count + ")";
while (lstNames.Any(i => i.Equals(label)))
{
var indexLabel = sourceLabel.Substring(sourceLabel.Length-2,1);
var maxIndex = sameNameList.Max(i =>int.Parse( i.Substring(sourceLabel.Length - 2, 1)));
int labelCount = maxIndex + 1;
label = labelSubstring + labelCount + ")";
}
}
return label;
}
Actual Input:
EC(2)
Expected output:
EC(3)
I have tried with some logic but it was not working with all input strings. It worked for few cases only.
Please help me on this.
https://dotnetfiddle.net/dFrzhA
public static void Main() {
List<string> lstNames= new List<string>{"Ecard","EC","EC(1)","EC(2)","NCard(1)"};
var copiedValue= GetNewCopiedValue(lstNames, "EC(1)");
Console.WriteLine("Copied Text is :" + copiedValue);
}
public static string GetNewCopiedValue(List<string> lstNames, string ValueToCopyInList) {
string newName;
if (!lstNames.Contains(ValueToCopyInList)) {
newName = ValueToCopyInList;
} else {
int? suffix = ParseSuffix(ValueToCopyInList);
string baseName = suffix == null ? ValueToCopyInList : ValueToCopyInList.Substring(0, ValueToCopyInList.LastIndexOf('('));
suffix = suffix ?? 1;
newName = baseName + "(" + suffix + ")";
while (lstNames.Contains(newName)) {
suffix++;
newName = baseName + "(" + suffix + ")";
}
}
lstNames.Add(newName);
return newName;
}
public static int? ParseSuffix(string value) {
int output;
if (string.IsNullOrEmpty(value)) return null;
if (!value.EndsWith(")")) {
return null;
}
var idxStart = value.LastIndexOf('(');
var strResult = value.Substring(idxStart + 1, value.Length - (idxStart + 2));
if (int.TryParse(strResult, out output))
return output;
return null;
}

ArgumentOutOfRangeException: startIndex cannot be longer than the length of string

When I run the compiler it throws an exception:
ArgumentOutOfRangeException: startIndex cannot be longer than the
length of string.
I do not understand why, the string which I write into the compiler consists of 10 numbers, and i want the substring to pick the 9th number, but obviously I'm doing something wrong.
Example of string: 9303140456
Code:
public string kollaKön()
{
string siffraAsString = form.textBox3.Text.Substring(8, 1);
int siffraAsNum = int.Parse(siffraAsString);
int result = (siffraAsNum % 2);
if (result == 1)
{
return form.textBox5.Text = ("Är en Man");
}
else
{
return form.textBox5.Text = (" Är en Kvinna");
}
}
Complete code, maybe makes my mistake obvious:
namespace WindowsFormsApplication3
{
public class Person
{
Form1 form = new Form1();
string förnamn;
string efternamn;
string personnummer;
string Kön;
public Person(string förNamn, string efterNamn, string personNummer)
{
string förnamn = förNamn;
string efternamn = efterNamn;
string personnummer = personNummer;
}
static bool luhn(string personNummer)
{
int sum = 0;
for (int i = 0; i < personNummer.Length; i++)
{
int temp = (personNummer[i] - '0') << (1 - (i & 1));
if (temp > 9) temp -= 9;
sum += temp;
}
return (sum % 10) == 0;
}
public string kollaKön()
{
string debuggerIsMyFriend = form.textBox3.Text;
string siffraAsString = form.textBox3.Text.Substring(8, 1);
int siffraAsNum = int.Parse(siffraAsString);
int result = (siffraAsNum % 2);
if (result == 1)
{
return form.textBox5.Text = ("Är en Man");
}
else
{
return form.textBox5.Text = (" Är en Kvinna");
}
}
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
string förnamn = textBox1.Text;
string efternamn = textBox2.Text;
string personnummer = textBox3.Text;
string persnr = "";
if (personnummer.Length != 10)
{
persnr = " Personnummer är i fel format. ";
}
if (personnummer.Length == 10)
{
persnr = " Personnummers är i korrekt format.";
}
Person p1 = new Person(förnamn, efternamn, personnummer);
p1.kollaKön();
textBox4.Text = förnamn + " " + efternamn + " " + personnummer + " " + " " + persnr;
}
}
}
This line in your Person class
Form1 form = new Form1();
declares and initialize a new Instance of Form1. This instance is not the one that you have shown on your monitor. When you type your strings you type them on the instance that is shown on monitor not into the textboxes of this hidden instance.
Of course this means that when you write
string siffraAsString = form.textBox3.Text.Substring(8, 1);
you are taking the text of the hidden textbox that is empty and the following Substring code fails with the Index Out of Range Exception
You need to change you Person class and add properties that receive the content of the textboxes required for your calculations.
For example
public class Person
{
// Sorry but I have no idea of what Siffra means...
// change the name as you wish
public string Siffra {get;set;}
...... other properties
public string kollaKön()
{
// A defensive attitude is always a good practice.
if(string.IsNullOrEmpty(this.Siffra) ||
this.Siffra.Length < 10)
return "Invalid Siffra";
string siffraAsString = this.Siffra.Substring(8, 1);
int siffraAsNum = int.Parse(siffraAsString);
int result = (siffraAsNum % 2);
return (result == 1 ? "Är en Man" : " Är en Kvinna");
}
}
and in your button click on the form you run
.....
Person p1 = new Person(förnamn, efternamn, personnummer);
p1.Siffra = this.textBox3.Text;
string result = p1.kollaKön();
this.textBox5.Text = result;
Before all your code, add this line
string debuggerIsMyFriend = form.textBox3.Text;
Set a breakpoint on that line, run the code and hover the mouse over the variable to see what it actually contains, I bet it's not the 10 characters string you are expecting
You should handle this more gracefully. This will handle your edge cases properly.
The string you're getting in that TextBox is most certainly not 9 characters long or more, and unless you have 100% certainty that your input is 9 characters, you should handle it gracefully.
Rule of thumb: Don't try to access the index of an array without checking its length first.
...Second rule of thumb: Also make sure you're accessing the correct UI control if you think something's fishy.
public string kollaKön()
{
//string siffraAsString = form.textBox3.Text.Substring(8, 1);
int siffraAsNum = GetNinthNumber(form.textBox3.Text);
int result = (siffraAsNum % 2);
if (result == 1)
{
return form.textBox5.Text = ("Är en Man");
}
else
{
return form.textBox5.Text = (" Är en Kvinna");
}
}
public static int GetNinthNumber(string str)
{
string numberField = str.Trim();
if (numberField.Length < 9)
{
// Handle less than 9 cases
return 0;
}
else
{
int number;
bool isNumber = Int32.TryParse(str[8].ToString(), out number);
if (!isNumber)
{
throw new Exception("Value is not a number");
}
return number;
}
}
I'm very sure that your line string siffraAsString = form.textBox3.Text.Substring(8, 1); doesn't have 10 numbers.
Checks the value of form.textBox3.Text as say Jacopo.

c# Why won't the sum of variables from different classes amount in my code?

public static void Main(string[] args)
{
string name = "asfd";
int plhp = 100, plmp = 100, zenhp = 500;
Random rdn = new Random();
int atk = rdn.Next(10, 55);
int zatk = rdn.Next(20, 35);
while (plhp > 0 && zenhp > 0)
{
string action = Console.ReadLine();
if (String.Equals(action, "attack", StringComparison.OrdinalIgnoreCase))
{
zenhp -= atk;
Console.WriteLine("Zen has taken -" + atk.ToString() + " damage!");
actionofzen(plhp, name, zenhp, zatk);
Console.WriteLine("Your next move?");
}
else if (!(action == "attack" ))
{
Console.WriteLine("Invalid command.");
}
}
}
public static int actionofzen(int plhp, string name, int zenhp, int zatk)
{
Random rdn = new Random();
string[] zenmoves = { "attack" };
string zenaction = zenmoves[rdn.Next(zenmoves.Length)];
if (zenaction == "attack")
{
plhp -= zatk;
Console.WriteLine("Zen has countered, inflicting -" + zatk + " damage on " + name + ".");
}
return 0;
}
The problem is that whenever Zen does something, it doesn't affect the overall HP, like the plhp -= zatk; doesn't even do anything, only the player can affect Zen's health. How do I make these variables from different classes sum up? Also how do I simplify this while maintaining the use of StringComparison.OrdinalIgnoreCase?
if (action.Equals("attack", StringComparison.OrdinalIgnoreCase) ||
action.Equals("heal", StringComparison.OrdinalIgnoreCase))
You have to pass value by referance. so it can update the changes in the main method. Jus t pass the plhp with ref keyword Here is the working fiddle for it https://dotnetfiddle.net/amHbXF
public static void Main()
{
Console.WriteLine("Hello World");
string name = "asfd";
int plhp = 100, plmp = 100, zenhp = 500;
Random rdn = new Random();
int atk = rdn.Next(10, 55);
int zatk = rdn.Next(20, 35);
while (plhp > 0 && zenhp > 0)
{
string action = Console.ReadLine();
if (String.Equals(action, "attack", StringComparison.OrdinalIgnoreCase))
{
zenhp -= atk;
Console.WriteLine("Zen has taken -" + atk.ToString() + " damage!");
actionofzen(ref plhp, name, zenhp, zatk);
Console.WriteLine("Player HP: " +plhp);
Console.WriteLine("Zen HP: " +zenhp);
Console.WriteLine("Your next move?");
}
else if (!(action == "attack"))
{
Console.WriteLine("Invalid command.");
}
}
}
public static int actionofzen(ref int plhp, string name, int zenhp, int zatk)
{
Random rdn = new Random();
string[] zenmoves =
{
"attack"
}
;
string zenaction = zenmoves[rdn.Next(zenmoves.Length)];
if (zenaction == "attack")
{
plhp -= zatk;
Console.WriteLine("Zen has countered, inflicting -" + zatk + " damage on " + name + ".");
}
return 0;
}
See https://msdn.microsoft.com/en-us/library/14akc2c7.aspx for info on what is going on with plhp. In order for modifications to plhp to propagate back up to the caller, it must be passed as a ref type. Your code is passing it as a "copy" (the default for value types), meaning you can change it all you want in actionofzen and the caller will never see the changes. plhp will have the same value it had before you called the method.
I'm not aware of any way to simplify the string comparison. You could downcase both strings and just use the == operator, but I'm not sure that is simpler.

C# formatting output of methods from a class and no data is displayed now

So I wanted to format this text so it was being padded and was all nice and square not dependant on the length of different address sizes or names. However now that its in this format...nothing shows up in regard to the actuall variables and values.
Before I did
Console.WriteLine(emp[i].GetEmpName());
and it worked fine, it displayed the string stored in that method. now I am unsure where the disconnect is but it now is displaying a blank value such as
Employee Name:
EmployeeAddress:
so forth.
for (int i = 0; i < count; i++)
{
string eNum = "Employee Number: ";
string eName = "Emplyee Name: ";
string eAddress = "Employee Address: ";
Console.WriteLine("------------------------------------------------------------------------");
Console.Write("|");
Console.Write(eNum.PadRight(30), emp[i].GetEmpNum());
Console.Write("|\n");
Console.Write("|");
Console.Write(eName.PadRight(30), emp[i].GetEmpName());
Console.Write("|\n");
Console.Write("|");
Console.Write(eAddress.PadRight(30), emp[i].GetEmpAddress());
Console.Write("|\n");
//Console.Write();
//Console.Write();
Console.Write("|");
Console.Write("Net Pay: {0:f2}", emp[i].CalcSalary());
Console.WriteLine("\n------------------------------------------------------ ------------------\n\n");
}
The rest of the code is here if you want to see it. Again it works as long as you dont format the output.
Where did I go so horribly wrong?!?!
using System;
using System.IO;
namespace Proj10
{
class Program
{
const int ARRAY_TWO = 2;
static void Main()
{
int count = 0;
Employee[] emp = new Employee[10];
string environment = System.Environment.GetFolderPath
(System.Environment.SpecialFolder.Personal) + "\\";
Console.WriteLine("Enter a file name in My Documents: ");
string input = Console.ReadLine();
string path = environment + input;
StreamReader myFile = new StreamReader(path);
do
{
if (myFile.EndOfStream)
{
break;
}
int num = int.Parse(myFile.ReadLine());
string name = myFile.ReadLine();
string address = myFile.ReadLine();
string hourNworked = myFile.ReadLine();
double[] values = new double[ARRAY_TWO];
sort(hourNworked, ref values);
emp[count] = new Employee();
emp[count].SetEmpNum(num);
emp[count].SetEmpName(name);
emp[count].SetEmpAddress(address);
emp[count].SetEmpHrlyPay(values[0]);
emp[count].SetEmpHrsWrked(values[1]);
//while count < 10 && !myfile.EOF();
//print loop using count
//emp[0].GetEmpNum();
//emp[0].CalcSalary();
/*Integer[] number = new Integer[5];
for (int i = 0; i < 5; i++)
number[i] = new Integer(i);
for (int i = 0; i < 5; i++)
Console.WriteLine(number[i].GetValue());
*/
count++;
} while (count < 10);
Console.WriteLine("\n\nAuthor: Daniel Demers");
Console.WriteLine("CS 1400 X01\n");
for (int i = 0; i < count; i++)
{
string eNum = "Employee Number: ";
string eName = "Emplyee Name: ";
string eAddress = "Employee Address: ";
Console.WriteLine("------------------------------------------------------------------------");
Console.Write("|");
Console.Write(eNum.PadRight(30), emp[i].GetEmpNum());
Console.Write("|\n");
Console.Write("|");
Console.Write(eName.PadRight(30), emp[i].GetEmpName());
Console.Write("|\n");
Console.Write("|");
Console.Write(eAddress.PadRight(30), emp[i].GetEmpAddress());
Console.Write("|\n");
//Console.Write();
//Console.Write();
Console.Write("|");
Console.Write("Net Pay: {0:f2}", emp[i].CalcSalary());
Console.WriteLine("\n------------------------------------------------------------------------\n\n");
}
Console.ReadLine();
}
public static void sort(string hourNworked, ref double[] values)
{
char[] rules = { ' ' };
string[] splitArray = hourNworked.Split(rules);
values[0] = double.Parse(splitArray[0]);
values[1] = double.Parse(splitArray[1]);
}
public class Employee
{
private int empNum;
private string name;
private string address;
private double hrlyPay;
private double hrsWrkd;
private double GROSS;
private double overTime;
private double overTimePay;
private double overTimeHours;
private double NET;
private double regTime;
private double fTaxAmount;
private double sTaxAmount;
private const double FED_TAX = .20;
private const double STATE_TAX = .075;
private const double OT_MULTIPLYER = 1.5;
private const int FORTY_HOURS = 40;
public Employee()
{
empNum = 0;
}
public void SetEmpNum(int n)
{
empNum = n;
}
public int GetEmpNum()
{
return empNum;
}
public void SetEmpName(string n)
{
name = n;
}
public string GetEmpName()
{
return name;
}
public void SetEmpAddress(string a)
{
address = a;
}
public string GetEmpAddress()
{
return address;
}
public void SetEmpHrlyPay(double h)
{
hrlyPay = h;
}
public double GetEmpHrlyPay()
{
return hrlyPay;
}
public void SetEmpHrsWrked(double w)
{
hrsWrkd = w;
}
public double GetEmpHrsWrkd()
{
return hrsWrkd;
}
public double CalcSalary()
{
if (hrsWrkd > 40)
{
overTimeHours = hrsWrkd - FORTY_HOURS;
overTimePay = hrlyPay * OT_MULTIPLYER;
overTime = overTimePay * overTimeHours;
regTime = (hrsWrkd - overTimeHours) * hrlyPay;
GROSS = overTime + regTime;
fTaxAmount = (regTime + overTime) * FED_TAX;
sTaxAmount = (regTime + overTime) * STATE_TAX;
NET = GROSS - (fTaxAmount + sTaxAmount);
return NET;
}
else
{
regTime = hrlyPay * hrsWrkd;
fTaxAmount = regTime * FED_TAX;
sTaxAmount = regTime * STATE_TAX;
NET = regTime - (fTaxAmount + sTaxAmount);
return NET;
}
}
}
}
}
The Console.Write overload you are using takes a format string and an object. Since your first argument does not contain any placeholders, the second argument is not used.
Try this instead:
Console.WriteLine("|{0,-30}{1,-20}|", eNum, emp[i].GetEmpNum());
See it working online: ideone

Categories

Resources