Adding a Form to an existing console application? - c#

I need to add a form to my existing application i have it all laid out but how do I get it to use the code from the form as to make it seamless. Any thoughts? and sorry for the wall of code just thought it might help.
The Validate button should get its info from the console like below
The Generate action should append the check digit like in this example
public static void Main(string[] args)
{
Console.Write("Enter a valid 10 digit ISBN Number ");
string isbn = isbnChecker.DestabilizeIsbn(Console.ReadLine()); // Normalizes the input and puts it on string "str"
if (isbn.Length > 10 || isbn.Length < 9) // If the string length is greather than 10, or smaller than 9
{
Console.WriteLine("The number you have entered is not a valid ISBN try again."); // Print invalid number
Console.ReadLine();
}
else if (isbn.Length == 10) // If the length is 10
{
if (isbnChecker.CheckNumber(isbn)) // If function CheckNum return "true"...
Console.WriteLine("The number you have entered is a valid ISBN");
else // If it returns "false"...
Console.WriteLine("The number you have entered is not a valid ISBN try again.");
Console.ReadLine();
}
else // Else (If the number is NOT greater than 10 or smaller than 9, NOR is it 10 -> If the number is 9)
{
Console.WriteLine("The Check digit that corresponds to this ISBN number is " + checkIsbnClass.CheckIsbn(isbn) + "."); // Print the checksum digit
Console.ReadLine();
}
}
public static class isbnChecker
{
public static bool CheckNumber(string isbn) // Checks if the checksum digit is correct
{
if (isbn[9].ToString() == checkIsbnClass.CheckIsbn(isbn)) // If the 10th digit of the number is the same as the calculated digit...
return true;
else // If they're not the same...
return false;
}
public static string DestabilizeIsbn(string isbn) // replace the string
{
return isbn.Replace("-", "").Replace(" ", "");
}
}
public static string CheckIsbn(string isbn) // Calculates the 10th digit of a 9-digits partial ISBN number
{
int sum = 0;
for (int i = 0; i < 9; i++) // For each number...
{
sum += int.Parse(isbn[i].ToString()) * (i + 1); // ...Multiply the number by it's location in the string
}
if ((sum % 11) == 10) // If the remainder equals to 10...
{
return "x"; // Output X
}
else // If it does not equal to 10...
{
return (sum % 11).ToString(); // Output the number
}
}
public static bool CheckNumber(string isbn) // Checks if the checksum digit is correct
{
if (isbn[9].ToString() == CheckIsbn(isbn)) // If the 10th digit of the number is the same as the calculated digit...
return true;
else // If they're not the same...
return false;
}
public static string DestabilizeIsbn(string isbn) // replace the string
{
return isbn.Replace("-", "").Replace(" ", "");
}
}
public partial class IsbnForm : Form
{
public IsbnForm()
{
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
this.xInputTextBox.Text = "Enter a Valid ISBN";
}
}
}

I'm not sure what you're asking here. If you want the user to enter the ISBN in the form, then you'd do this:
using (var frm = new IsbnForm())
{
var rslt = frm.ShowDialog();
if (rslt == DialogResult.OK)
{
// Access property that gets the value the user entered.
}
else
{
// User canceled the form somehow, so show an error.
}
}
If you want to display the form and have the entry field displaying the ISBN that the user entered on the command line, then you'll need to add a property or method to the IsbnForm class so that you can set the value before displaying the form. That is, inside IsbnForm, add this property:
public string Isbn
{
get { return xInputTextBox.Text; }
set { xInputTextBox.Text = value; }
}
And then, to populate it:
Console.Write("Enter an ISBN: ");
var isbn = Console.ReadLine();
using (var frm = new IsbnForm())
{
frm.Isbn = isbn; // populates the field in the form.
var rslt = frm.ShowDialog();
// etc, etc.
}

Related

How to restrict decimal in a console calculator in C#? Like when a decimal is inputted, it should print an error. But no if doesn't

Can someone help me modify my work? Help me add:
An error message when the user tries to enter decimal values.
A third operand for the calculator.
An error message when the user tries to enter any string value other than “exit”.
Here's my code:
class Program
{
static void Main(string[] args)
{
do
{
Console.Write("x = ");
string str = Console.ReadLine();
if (str == "exit")
{
Console.WriteLine("The Programme has stopped");
continue;
}
else
{
int x = Convert.ToInt32(str);
Console.Write("y = ");
int y = Convert.ToInt32(Console.ReadLine());
int sum = x / y;
Console.WriteLine("Result: {0}", sum);
}
}
while (true);
}
}
I'd be very grateful.
Here is a function you can use:
public static bool HasDecimals(decimal x) {
return Decimal.Round(x, 0) != x;
}
If I were going to do this, I'd create a function that I can use to handle most of the user interaction (emitting the prompt, parsing the input string, deciding if "Exit" was entered). In the code below, I kinda-sorta use the standard TryGetXxx pattern.
In this code below, if the TryGetDecimalValueWithPrompt returns true, then a properly parsed number is returned in the output. If it returns false, then the user has chosen to quit.
So, I start with that function:
public static bool TryGetDecimalValueWithPrompt(string prompt, out decimal outputValue)
{
while (true)
{
Console.Write(prompt + " > ");
var response = Console.ReadLine();
if (response.Equals("exit", StringComparison.OrdinalIgnoreCase) || response.Equals("quit", StringComparison.OrdinalIgnoreCase))
{
outputValue = 0.0m;
return false;
}
if (decimal.TryParse(response, out outputValue))
{
return true;
}
//otherwise, failure, so try again
Console.WriteLine("Sorry, incorrect format, try entering a correctly formatted decimal again");
}
}
The while(true) statement says Loop Forever. In this case, Forever lasts until the user has entered a properly formatted number or one of the "exit" keywords.
Then I construct my program around it:
if (!TryGetDecimalValueWithPrompt("Enter the first operand", out var operand1))
{
return;
}
if (!TryGetDecimalValueWithPrompt("Enter the second operand", out var operand2))
{
return;
}
if (operand2 == 0.0m)
{
Console.WriteLine("Sorry, you can't divide by zero");
return;
}
Console.WriteLine($"The result of op1/op2 is {operand1 / operand2}");
If you don't want to allow decimals being entered, change the TryGetDecimalValueWithPrompt function to work with integers instead:
public static bool TryGetIntValueWithPrompt(string prompt, out int outputValue)
{
while (true)
{
Console.Write(prompt + " > ");
var response = Console.ReadLine();
if (response.Equals("exit", StringComparison.OrdinalIgnoreCase) || response.Equals("quit", StringComparison.OrdinalIgnoreCase))
{
outputValue = 0;
return false;
}
if (int.TryParse(response, out outputValue))
{
return true;
}
//otherwise, failure, so try again
Console.WriteLine("Sorry, incorrect format, try entering a correctly formatted integer again");
}
}
If you work with integers, remember that integer division always yields an integer. For example, if you use integers in 7 / 2, the result will be 3, not 3.5. If you want 3.5, do something like 7 / (decimal) 2 (at that point, you are dividing an integer by a decimal and you'll get a decimal).
By the way, if you wanted to prompt for the operator (+, -, *, or /), you could create a TryGetOperator function in the same pattern and just check whatever you get from the user with something like:
var operators = new[] { "+", "-", "*", "/" };
bool goodOperator = operators.Contains(inputFromUser);

C# string to array from readline issue

I am doing some C# exercises, the assignment is to check if att Swedish SSN is issued to a woman or a man.
The algorithm checks if the ninth number is equally dividable by 0, then it's a woman or else a man.
If I use a hardcoded "nr" in a string variable, the algorithm works, but if I try to read it from a readline statement, I get the following error:
Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: startIndex
This is the code I am using:
//string personnr = "860215-2097";
string personnr = "";
char[] arr;
public void CheckGender(string pnr)
{
arr = personnr.ToCharArray(9, 1);
if (personnr[9] %2 == 0)
{
Console.WriteLine($"Woman!!!");
}
else
{
Console.WriteLine($"Man!!!");
}
}
public void PrintPersonNr()
{
Console.WriteLine("Write a personnr in the format yymmdd-nnnn: ");
string nr = Console.ReadLine();
CheckGender(nr);
}
So it's my PrintPersonNr method that's not working properly I guess..
You can try this:
public enum SSNGender
{
Female,
Male
}
class Program
{
static public Dictionary<SSNGender, string> SSNGenderText
= new Dictionary<SSNGender, string>()
{
{ SSNGender.Female, "Woman" },
{ SSNGender.Male, "Man" },
};
static public SSNGender CheckSSNGender(string pnr)
{
// Here check the validity of the pnr (length, format...)
return pnr[9] % 2 == 0 ? SSNGender.Female : SSNGender.Male;
}
static void Main(string[] args)
{
Console.WriteLine("Write a personnr in the format yymmdd-nnnn: ");
string nr = Console.ReadLine();
var result = CheckSSNGender(nr);
Console.WriteLine(SSNGenderText[result]);
Console.ReadKey();
}
Try following :
public void CheckGender(string pnr)
{
string arr = pnr.Substring(10, 1);
if (arr == "0")
{
Console.WriteLine("Woman!!!");
}
else
{
Console.WriteLine("Man!!!");
}
}
What you need to do is to use the modulus operator and then to check if this number is then divisible by two and if the result is zero then it is even.
There is a fundamental issue as well, you would need to check if the character is a number or not. if it is then the operation would need to then be completed, if not you need to let the user know.
I have modified JDWeng post
public void CheckGender(string pnr)
{
string arr = pnr.Substring(9, 1);
int num =0;
if (int.TryParse(arr, num))
{
if ((num % 2) == "0")
{
Console.WriteLine("Man!!!");
}
else
{
Console.WriteLine("Woman!!!");
}
}
else
{
Console.WriteLine("Not a number!");
}
}
Best of luck in your exercise as well!!!

how to only have numbers stored in an string array in console application

So, I am trying to create a pizza ordering program for my school project which requires the customer/user to input their details e.g name phone number address and what not. I store all those information into a string array, but how to I only allow numbers to be entered into the phone number section. I tried using a method which I have been provided with but it doesn't seem to work it just errors.
Here is my current code
public static string[] GetCustInfo(string [] custInfo)
{
start:
bool success = false;
Console.Write("\n" + "Please input D for Delivery OR P for Pickup($3 for Delivery): " + "\n");
custInfo[0] = Console.ReadLine();
while (success != true)
{
if (custInfo[0] == "D" || custInfo[0] == "d")
{
custInfo[1] = ReadString("Please enter your name: ");
Console.Write(Readint("Please enter your Ph No. : "));
custInfo[2] = Console.ReadLine();
custInfo[3] = ReadString("Please enter your adress: ");
success = true;
}
else if (custInfo[0] == "P" || custInfo[0] == "p")
{
custInfo[1] = ReadString("Please enter your name: ");
success = true;
}
else
{
goto start;
}
}
return custInfo;
}
Here are the methods I am using to prevent the user from entering a number or letter:
public static int Readint(String prompt)
{
int userInput = 0;
Boolean success = false;
while (!success)
{
Console.Write(prompt);
try
{
userInput = Convert.ToInt32(Console.ReadLine());
success = true;
}
catch
{
Console.WriteLine("Please Enter a VALID NUMBER");
}
}
return userInput;
}
public static string ReadString(String prompt)
{
string userInput = " ";
Boolean success = false;
while (!success)
{
Console.Write(prompt);
try
{
userInput = Console.ReadLine();
if (userInput.Length <= 20 && userInput.Length>1)
{
success = true;
foreach (char charcter in userInput)
{
if (Char.IsNumber(charcter) || Char.IsSymbol(charcter) || Char.IsPunctuation(charcter))
{
success = false;
}
}
}
if (success == false)
{
Console.WriteLine("Please enter a valid input!" + "\n");
}
else
{
success = true;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
return userInput;
}
I tried inserting:
custInfo[2] = Readint("Please enter your Ph No.");
but it just gave me an error saying:
"cannot implicate type int to string"
but how to I only allow numbers to be entered into the phone number
You ReadInt method already takes care of this point with the while-loop and the try/catch clause. If you want to store this information into the array you need to get your number into the correct/fitting data type for the array saying: string. You return value of ReadInt is an int and this class has an implementation of the ToString method which in your case would convert the int into a string. So you can simply call it on the returnvalue of ReadInt:
custInfo[1] = ReadString("Please enter your name: ");
custInfo[2] = Readint("Please enter your Ph No.").ToString();
custInfo[3] = ReadString("Please enter your adress: ");
Insted of public static string[] GetCustInfo(string [] custInfo), you might add array of an objects, but keep in mind next : Object array store elements of different types in a single collection. An object reference can point to any derived type instance.
Whatever you could do this :
object[] array1 = new object[5];
array1[0] = new object();
array1[1] = new StringBuilder("Initialized");
array1[2] = "String literal";
array1[3] = 3;
array1[4] = null;
So in your case: this might look like this
public static object[] GetCustInfo(object [] custInfo)
You trying to insert an int value into string array..surely make sense that you convert the value into a string?

Restricting user input to numbers only

Brand new to C# [4 hours new :)], but hoping for some pointers on a Board Feet Calculator restricting the user input to only numbers, not allow letters or special characters.
First, does the restriction take place in the Class, Method, and/or Program? (I believe Class and Method)
Second, I've seen an example below, would I use something similar to this?
Third, if so, do I need to make separate classes for KeyPress and KeyPressEventArgs? (I believe they automatically there e.g.
public char KeyChar { get; set; }
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
// allows only letters
if (!char.IsLetter(e.KeyChar))
{
e.Handled = true;
}
}
My Program
namespace BoardFt_MyTry_
{
class Program
{
static void Main(string[] args)
{
Board board = new Board();
board.lengthOfboard = Convert.ToDouble(askQuestion("What is the length of your board in inches?"));
board.widthOfboard = Convert.ToDouble(askQuestion("What is the width of your board in inches?"));
board.thicknessOfboard = Convert.ToDouble(askQuestion("What is the thickness of your board in inches?"));
Console.WriteLine("Your board has {0} board feet.", board.CalcBoardFt());
Console.ReadLine();
}
private static string askQuestion(string question)
{
Console.WriteLine(question);
return Console.ReadLine();
}
}
My Board Class
namespace BoardFt_MyTry_
{
class Board
{
public double lengthOfboard;
public double widthOfboard;
public double thicknessOfboard;
public double CalcBoardFt()
{
double boardft = 0;
boardft = (this.lengthOfboard * this.widthOfboard * this.thicknessOfboard) / 144;
return boardft;
}
}
}
You can't really do that in a console application. All you can do is allow the user to input the bad data, then tell the user that the data is bad.
You can try something like this:
class Program
{
public double AskDnoubleQuestion(string message){
do {
Console.Write(message);
var input = Console.ReadLine();
if (String.IsNullOrEmpty(input)){
Console.WriteLine("Input is required");
continue;
}
double result;
if (!double.TryParse(input, out result)){
Console.WriteLine("Invalid input - must be a valid double");
continue;
}
return result;
}
static void Main(string[] args)
{
Board board = new Board();
board.lengthOfboard = AskDoubleQuestion("What is the length of your board in inches?");
board.widthOfboard = AskDoubleQuestion(askQuestion("What is the width of your board in inches?");
board.thicknessOfboard = AskDoubleQuestion(askQuestion("What is the thickness of your board in inches?");
Console.WriteLine("Your board has {0} board feet.", board.CalcBoardFt());
Console.ReadLine();
}
In case validation is not the way you want to proceed, you could do something like this:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter a number:");
string number = ReadNumber();
Console.WriteLine("You entered: " + number);
}
private static string ReadNumber()
{
string input = "";
do
{
ConsoleKeyInfo keyInfo = Console.ReadKey(true);
if (char.IsNumber(keyInfo.KeyChar))
{
input = input + keyInfo.KeyChar;
Console.Write(keyInfo.KeyChar);
}
if (keyInfo.Key == ConsoleKey.Enter)
{
Console.WriteLine();
break;
}
if (keyInfo.Key == ConsoleKey.Backspace)
{
input = input.Substring(0, input.Length - 1);
Console.Write("\b \b");
}
} while (true);
return input;
}
}
This will allow the user to enter only numbers. You could filter it anyway you want, if you wanted to. For example, only letters and numbers, etc...
As it stands right now, it only allows integer numbers. If you want to allow a decimal point, change the line above to this: if (char.IsNumber(keyInfo.KeyChar) || keyInfo.KeyChar == '.')
You could write a method that reads key by key (not displaying in the console), ignores non-numeric characters, prints valid characters and appends them to a StringBuilder instance, like so:
public static string ReadOnlyNumbers()
{
StringBuilder input = new StringBuilder();
ConsoleKeyInfo ckey;
while ((ckey = Console.ReadKey(true)).Key != ConsoleKey.Enter)
{
if (Char.IsDigit(ckey.KeyChar))
{
Console.Write(ckey.KeyChar);
input.Append(ckey.KeyChar);
}
if (ckey.Key == ConsoleKey.Backspace)
{
input.Length--;
Console.Write("\b \b");
}
}
Console.Write(Environment.NewLine);
return input.ToString();
}
You could then use it like this:
string input = ReadOnlyNumbers();
Console.WriteLine(input);

Program to find minimum number in string

I have a c# class like so
internal class QueuedMinimumNumberFinder : ConcurrentQueue<int>
{
private readonly string _minString;
public QueuedMinimumNumberFinder(string number, int takeOutAmount)
{
if (number.Length < takeOutAmount)
{
throw new Exception("Error *");
}
var queueIndex = 0;
var queueAmount = number.Length - takeOutAmount;
var numQueue = new ConcurrentQueue<int>(number.ToCharArray().Where(m => (int) Char.GetNumericValue(m) != 0).Select(m=>(int)Char.GetNumericValue(m)).OrderBy(m=>m));
var zeroes = number.Length - numQueue.Count;
while (queueIndex < queueAmount)
{
int next;
if (queueIndex == 0)
{
numQueue.TryDequeue(out next);
Enqueue(next);
} else
{
if (zeroes > 0)
{
Enqueue(0);
zeroes--;
} else
{
numQueue.TryDequeue(out next);
Enqueue(next);
}
}
queueIndex++;
}
var builder = new StringBuilder();
while (Count > 0)
{
int next = 0;
TryDequeue(out next);
builder.Append(next.ToString());
}
_minString = builder.ToString();
}
public override string ToString() { return _minString; }
}
The point of the program is to find the minimum possible integer that can be made by taking out any x amount of characters from a string(example 100023 is string, if you take out any 3 letters, the minimum int created would be 100). My question is, is this the correct way to do this? Is there a better data structure that can be used for this problem?
First Edit:
Here's how it looks now
internal class QueuedMinimumNumberFinder
{
private readonly string _minString;
public QueuedMinimumNumberFinder(string number, int takeOutAmount)
{
var queue = new Queue<int>();
if (number.Length < takeOutAmount)
{
throw new Exception("Error *");
}
var queueIndex = 0;
var queueAmount = number.Length - takeOutAmount;
var numQueue = new List<int>(number.Where(m=>(int)Char.GetNumericValue(m)!=0).Select(m=>(int)Char.GetNumericValue(m))).ToList();
var zeroes = number.Length - numQueue.Count;
while (queueIndex < queueAmount)
{
if (queueIndex == 0)
{
var nextMin = numQueue.Min();
numQueue.Remove(nextMin);
queue.Enqueue(nextMin);
} else
{
if (zeroes > 1)
{
queue.Enqueue(0);
zeroes--;
} else
{
var nextMin = numQueue.Min();
numQueue.Remove(nextMin);
queue.Enqueue(nextMin);
}
}
queueIndex++;
}
var builder = new StringBuilder();
while (queue.Count > 0)
{
builder.Append(queue.Dequeue().ToString());
}
_minString = builder.ToString();
}
public override string ToString() { return _minString; }
}
A pretty simple and efficient implementation can be made, once you realize that your input string digits map to the domain of only 10 possible values: '0' .. '9'.
This can be encoded as the number of occurrences of a specific digit in your input string using a simple array of 10 integers: var digit_count = new int[10];
#MasterGillBates describes this idea in his answer.
You can then regard this array as your priority queue from which you can dequeue the characters you need by iteratively removing the lowest available character (decreasing its occurrence count in the array).
The code sample below provides an example implementation for this idea.
public static class MinNumberSolver
{
public static string GetMinString(string number, int takeOutAmount)
{
// "Add" the string by simply counting digit occurrance frequency.
var digit_count = new int[10];
foreach (var c in number)
if (char.IsDigit(c))
digit_count[c - '0']++;
// Now remove them one by one in lowest to highest order.
// For the first character we skip any potential leading 0s
var selected = new char[takeOutAmount];
var start_index = 1;
selected[0] = TakeLowest(digit_count, ref start_index);
// For the rest we start in digit order at '0' first.
start_index = 0;
for (var i = 0; i < takeOutAmount - 1; i++)
selected[1 + i] = TakeLowest(digit_count, ref start_index);
// And return the result.
return new string(selected);
}
private static char TakeLowest(int[] digit_count, ref int start_index)
{
for (var i = start_index; i < digit_count.Length; i++)
{
if (digit_count[i] > 0)
{
start_index = ((--digit_count[i] > 0) ? i : i + 1);
return (char)('0' + i);
}
}
throw new InvalidDataException("Input string does not have sufficient digits");
}
}
Just keep a count of how many times each digit appears. An array of size 10 will do. Count[i] gives the count of digit i.
Then pick the smallest non-zero i first, then pick the smallest etc and form your number.
Here's my solution using LINQ:
public string MinimumNumberFinder(string number, int takeOutAmount)
{
var ordered = number.OrderBy(n => n);
var nonZero = ordered.SkipWhile(n => n == '0');
var zero = ordered.TakeWhile(n => n == '0');
var result = nonZero.Take(1)
.Concat(zero)
.Concat(nonZero.Skip(1))
.Take(number.Length - takeOutAmount);
return new string(result.ToArray());
}
You could place every integer into a list and find all possible sequences of these values. From the list of sequences, you could sort through taking only the sets which have the number of integers you want. From there, you can write a quick function which parses a sequence into an integer. Next, you could store all of your parsed sequences into an array or an other data structure and sort based on value, which will allow you to select the minimum number from the data structure. There may be simpler ways to do this, but this will definitely work and gives you options as far as how many digits you want your number to have.
If I'm understanding this correctly, why don't you just pick out your numbers starting with the smallest number greater than zero. Then pick out all zeroes, then any remaining number if all the zeroes are picked up. This is all depending on the length of your ending result
In your example you have a 6 digit number and you want to pick out 3 digits. This means you'll only have 3 digits left. If it was a 10 digit number, then you would end up with a 7 digit number, etc...
So have an algorithm that knows the length of your starting number, how many digits you plan on removing, and the length of your ending number. Then just pick out the numbers.
This is just quick and dirty code:
string startingNumber = "9999903040404"; // "100023";
int numberOfCharactersToRemove = 3;
string endingNumber = string.Empty;
int endingNumberLength = startingNumber.Length - numberOfCharactersToRemove;
while (endingNumber.Length < endingNumberLength)
{
if (string.IsNullOrEmpty(endingNumber))
{
// Find the smallest digit in the starting number
for (int i = 1; i <= 9; i++)
{
if (startingNumber.Contains(i.ToString()))
{
endingNumber += i.ToString();
startingNumber = startingNumber.Remove(startingNumber.IndexOf(i.ToString()), 1);
break;
}
}
}
else if (startingNumber.Contains("0"))
{
// Add any zeroes
endingNumber += "0";
startingNumber = startingNumber.Remove(startingNumber.IndexOf("0"), 1);
}
else
{
// Add any remaining numbers from least to greatest
for (int i = 1; i <= 9; i++)
{
if (startingNumber.Contains(i.ToString()))
{
endingNumber += i.ToString();
startingNumber = startingNumber.Remove(startingNumber.IndexOf(i.ToString()), 1);
break;
}
}
}
}
Console.WriteLine(endingNumber);
100023 starting number resulted in 100 being the end result
9999903040404 starting number resulted in 3000044499 being the end result
Here's my version to fix this problem:
DESIGN:
You can sort your list using a binary tree , there are a lot of
implementations , I picked this one
Then you can keep track of the number of the Zeros you have in your
string Finally you will end up with two lists: I named one
SortedDigitsList and the other one ZeroDigitsList
perform a switch case to determine which last 3 digits should be
returned
Here's the complete code:
class MainProgram2
{
static void Main()
{
Tree theTree = new Tree();
Console.WriteLine("Please Enter the string you want to process:");
string input = Console.ReadLine();
foreach (char c in input)
{
// Check if it's a digit or not
if (c >= '0' && c <= '9')
{
theTree.Insert((int)Char.GetNumericValue(c));
}
}
//End of for each (char c in input)
Console.WriteLine("Inorder traversal resulting Tree Sort without the zeros");
theTree.Inorder(theTree.ReturnRoot());
Console.WriteLine(" ");
//Format the output depending on how many zeros you have
Console.WriteLine("The final 3 digits are");
switch (theTree.ZeroDigitsList.Count)
{
case 0:
{
Console.WriteLine("{0}{1}{2}", theTree.SortedDigitsList[0], theTree.SortedDigitsList[1], theTree.SortedDigitsList[2]);
break;
}
case 1:
{
Console.WriteLine("{0}{1}{2}", theTree.SortedDigitsList[0], 0, theTree.SortedDigitsList[2]);
break;
}
default:
{
Console.WriteLine("{0}{1}{2}", theTree.SortedDigitsList[0], 0, 0);
break;
}
}
Console.ReadLine();
}
}//End of main()
}
class Node
{
public int item;
public Node leftChild;
public Node rightChild;
public void displayNode()
{
Console.Write("[");
Console.Write(item);
Console.Write("]");
}
}
class Tree
{
public List<int> SortedDigitsList { get; set; }
public List<int> ZeroDigitsList { get; set; }
public Node root;
public Tree()
{
root = null;
SortedDigitsList = new List<int>();
ZeroDigitsList = new List<int>();
}
public Node ReturnRoot()
{
return root;
}
public void Insert(int id)
{
Node newNode = new Node();
newNode.item = id;
if (root == null)
root = newNode;
else
{
Node current = root;
Node parent;
while (true)
{
parent = current;
if (id < current.item)
{
current = current.leftChild;
if (current == null)
{
parent.leftChild = newNode;
return;
}
}
else
{
current = current.rightChild;
if (current == null)
{
parent.rightChild = newNode;
return;
}
}
}
}
}
//public void Preorder(Node Root)
//{
// if (Root != null)
// {
// Console.Write(Root.item + " ");
// Preorder(Root.leftChild);
// Preorder(Root.rightChild);
// }
//}
public void Inorder(Node Root)
{
if (Root != null)
{
Inorder(Root.leftChild);
if (Root.item > 0)
{
SortedDigitsList.Add(Root.item);
Console.Write(Root.item + " ");
}
else
{
ZeroDigitsList.Add(Root.item);
}
Inorder(Root.rightChild);
}
}

Categories