Using multiple classes - c#

I am trying to make a simple program that asks the user to enter an integer. Once the program receives the input it takes and stores it and then counts from 1 to the input integer and sums the total of the count. Then it displays the results in a meaningful way to the user and prompts them if they would like to process another number. The point of this program is to use loops and multiple classes. I know that I am really close to the desired end product but cannot figure out why the AccumulateValue() method is not working properly. It does not seem to be going into the conditional while statement that I made. If anyone could give me some insight to my problem that would be great!
Here is my code:
AccumulatorApp.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Project
{
class AccumulatorApp
{
static void Main(string[] args)
{
string loopControl = "Y";
int sum;
int enteredValue;
DisplayTitle();
while (loopControl == "Y" || loopControl == "YES")
{
enteredValue = InputInteger(0);
Accumulator number = new Accumulator(enteredValue);
sum = number.AccumulateValues();
DisplayOutput(sum, enteredValue);
Console.Write("\tWould you like to process another number? \n\t\t<Y or N>: ");
loopControl = Console.ReadLine().ToUpper();
}
}
public static void DisplayTitle()
{
Console.BackgroundColor = ConsoleColor.White;
Console.ForegroundColor = ConsoleColor.Black;
Console.Clear();
Console.WriteLine();
Console.WriteLine("\tProgramming Assignment 05 - Accumulator - Robert");
DrawLine();
}
public static int InputInteger(int enteredValue)
{
Console.Write("\tPlease enter a positive integer: ");
enteredValue = Convert.ToInt32(Console.ReadLine());
if (enteredValue > 0)
{
return enteredValue;
}
else
{
Console.WriteLine("\tInvalid input. Please enter a POSITIVE integer: ");
enteredValue = Convert.ToInt32(Console.ReadLine());
}
return enteredValue;
/*
Console.Write("Please enter a positive integer: ");
int enteredValue = Convert.ToInt32(Console.ReadLine());
return enteredValue;
* */
}
public static void DisplayOutput(int sum, int inputValue)
{
Console.WriteLine("\tThe inputed integer is: {0}", inputValue);
Console.WriteLine("\tThe sum of 1 through {0} = {1}", inputValue, sum);
DrawLine();
}
public static void DrawLine()
{
Console.WriteLine("\t______________________________________________________");
Console.WriteLine();
}
}
}
Accumulator.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Project
{
class Accumulator
{
int integerEntered;
public Accumulator()
{
}
public Accumulator(int integerEntered)
{
int enteredInteger = integerEntered;
}
public int AccumulateValues()
{
int accumulatedValue = 0;
int counterValue = 1;
while (counterValue <= integerEntered)
{
Console.WriteLine("\tPasses through loop = {0}", accumulatedValue);
accumulatedValue = accumulatedValue + counterValue;
counterValue = counterValue + 1;
}
return accumulatedValue;
}
}
}

When you are instantiating a new instance of Accumulator through it's constructor containing one int argument you were setting the passed value equal to the field within the class (Setting them both to 0.)
Your accumulator class should look like this:
class Accumulator
{
int integerEntered;
public Accumulator()
{
}
public Accumulator(int passedInteger)
{
//Local field is equal to passedInteger, not the other way around.
integerEntered = passedInteger;
}
public int AccumulateValues()
{
int accumulatedValue = 0;
int counterValue = 1;
while (counterValue <= integerEntered)
{
Console.WriteLine("\tPasses through loop = {0}", accumulatedValue);
accumulatedValue = accumulatedValue + counterValue;
//Increment does the same thing you were doing
counterValue++;
}
return accumulatedValue;
}
}

It looks like the problem may actually be with your value constructor. When this line is called:
Accumulator number = new Accumulator(enteredValue);
A new Accumulator is being made with your value constructor:
public Accumulator(int integerEntered)
{
int enteredInteger = integerEntered;
}
The problem is that integerEntered isn't really saved anywhere and once enteredInteger goes out of scope (end of constructor), the value that was entered is essentially lost as far as the Accumulator object is concerned. I think what you want is:
public Accumulator(int integerEntered)
{
integerEntered = integerEntered;
}
As a heads up, you may have to do this.integerEntered = integerEntered;
Also I think you want to subtract 1 from integerEntered each iteration of your while loop in AccumulateValues().

There 2 -3 things needs to be changed
1) you are not assigning values to integerEntered in your constructor so I have changed it
2) you should integerEntered as a property so i have changed it to public int integerEntered { get; set; }
3) the logic of calculating to count AccumulateValues .. actually mathematical formula is the sum up to integer n is = (n * (n+1))/2 so i have changed it too
try this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Project
{
class Accumulator
{
public int integerEntered { get; set; }
public Accumulator()
{
}
public Accumulator(int integerPassed)
{
integerEntered = integerPassed;
}
public int AccumulateValues()
{
int accumulatedValue = 0;
if(integerEntered > 0)
{
accumulatedValue = (integerEntered * (integerEntered + 1))/2;
}
return accumulatedValue;
}
}
}

Related

How to add a second argument(Number) to a calculator program?

I'm working on a small calculator program in Unity.
I only need the calculator to work with two numbers.
The feature I'm trying to implement:
After inputting the math operator, It should display the second number in the third index.
The issue:
Instead of Adding a second number, the first number is being overwritten if a different number is pressed on the keyboard.
Here's the script I've created:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Functions : MonoBehaviour
{
// Global Variable to display text on top panel
public Text panelText;
// Create a number variable
string num;
string num1;
string num2;
string mOpr;
string calNum;
string cbutton;
string opr;
bool isFirstNum;
// Start is called before the first frame update
void Start()
{
}
// A function with an int argument
public void NumberInputOne(string num)
{
num1 = num;
num2 = num;
if (panelText.text.Length < 1)
{
Debug.Log(num1);
panelText.text = num1;
isFirstNum = false;
}
else if (panelText.text.Length > 1 && panelText.text.Length < 3)
{
num2 = num;
Debug.Log(num2);
panelText.text = num1 + mOpr + num2;
}
}
public void OperatorInput(string opr)
{
mOpr = opr;
if (panelText.text.Length > 0 && panelText.text.Length < 2)
{
panelText.text = num1 + mOpr;
}
}
// public void NumberInputTwo(int num)
//{
// ResNum2 = num;
// Debug.Log(ResNum2);
// if (panelText.text.Length > 1 && panelText.text.Length < 3)
// {
// panelText.text = ResNum1 + opr + ResNum2;
// }
// }
public void RestartCal(string cButton)
{
panelText.text = "";
}
}
I've also added a screen recording to capture the issue:
First number being overwritten
Do you have any suggestions?
Thank you
use the NumberInputOne func like below;
public void NumberInputOne(string num)
{
if (num1 is null)
{
Debug.Log(num1);
panelText.text = num1;
num1 = num
}
else
{
num2 = num;
Debug.Log(num2);
panelText.text = num1 + mOpr + num2;
}
}
btw i recommend that you review the sample calculation application codes. because apart from what you're asking, there are places you need to improve in general.
This feels like a beginner programming exercise. But the right way to build a calculator involves programming concepts that you probably haven't been taught yet. Which makes this a poor choice as an assignment.
Personally I would build a calculator by defining a simple syntax tree to represent the formula being input. Including methods to display the formula and calculate the answer. For example;
public interface IValue
{
int Calculate();
string PrintValue();
}
public class Number : IValue
{
public int? Value;
public void AddDigit(int digit) => Value = (Value ?? 0) * 10 + digit;
public int Calculate() => Value ?? 0;
public string PrintValue() => Value?.ToString();
}
public abstract class BinaryOperator : IValue
{
public IValue Left;
public IValue Right;
public abstract int Operation(int left, int right);
public abstract char Operator { get; }
public int Calculate()
{
var left = Left.Calculate();
var right = Right.Calculate();
return Operation(left, right);
}
public string PrintValue() => $"{Left?.PrintValue()} {Operator} {Right?.PrintValue()}";
}
public class Addition : BinaryOperator
{
public override char Operator => '+';
public override int Operation(int left, int right) => left + right;
}
// TODO define other operators
Then think about how each button should change the syntax tree.
// the entire formula
public IValue Root;
// the number currently being typed
public Number Input;
public void Display() {
panelText.text = Root.PrintValue();
}
// start / clear
public void Start(){
Root = Input = new Number(){
Value = 0
};
Display();
}
public void Plus(){
// left as an exercise for the reader
Display();
}
public void Digit(int digit) {
Input.AddDigit(digit);
Display();
}
public void Calculate() {
// left as an exercise for the reader
Display();
}

C# Error: "A namespace cannot directly contain members such as fields or methods"

A method receiving 2 numbers and I need to return the numbers of common digits for them. For example, the numbers 2201 and 3021 returns 3 because these numbers have 3 common digits: 0, 1, and 2.
I get this error and don't understand it: A namespace cannot directly contain members such as fields or methods
Here is the code:
public static int AlphaRomeo(int a, int b)
{
int count = 0;
while (a > 0)
{
int tempa = a % 10;
a = a / 10;
int tempb = b % 10;
b = b / 10;
if (tempa == tempb)
count++;
}
return count;
}
Might be easier to avoid the mathematics:
private static string _digits = "0123456789";
public static int AlphaRomeo(int a, int b)
{
string aStr = a.ToString();
string bStr = b.ToString();
int common = 0;
for (int i = 0; i < _digits.Length; i++)
{
if (aStr.Contains(_digits[i]) && bStr.Contains(_digits[i]))
common++;
}
return common;
}
Consider this example, you don't have a class in your code:
using System; // Imports
namespace LearnClasses // Namespace
{
class Program //class
{
static void Main(string[] args) // Method 1
{
Console.WriteLine( AlphaRomeo(2201, 3021));
}
public static int AlphaRomeo(int a, int b) // Method 2
{
int count = 0;
// Your code
return count;
}
}
}

C# Delegates. Casting not working for some reason

2 Errors appear when I try to build this code.
First one: "Argument 2 : cannot convert from double to int."
Second one: "The best overloaded method for CalculatePay(double, int, Calculate) has some invalid arguments.
I don't understand why the casting I've applied in the BankHolidayShift and NormalShift methods isn't working. Thanks.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication8
{
public delegate int Calculate(double val1, int val2);
class PayCalculator
{
static double HourlyPay = 10;
static int HoursPerShift = 8;
static int NormalShift(double HourlyPay, int HoursPerShift)
{
return (int) HourlyPay * HoursPerShift;
}
static int BankHolidayShift(double HourlyPay, int HoursPerShift)
{
return (int)(HourlyPay * HoursPerShift) + 50;
}
public static int CalculatePay(double a, int b, Calculate calc)
{
int TotalPay = calc(a, b);
return TotalPay;
}
static void Main()
{
Calculate calc = new Calculate(BankHolidayShift);
int TotalPay = CalculatePay(HourlyPay, HourlyPay, calc);
Console.WriteLine("Total Pay for this shift is : {0}", TotalPay);
Console.ReadLine();
}
}
}
You have int TotalPay = CalculatePay(HourlyPay, HourlyPay, calc);, obviously it's a spelling, and you should have:
int TotalPay = CalculatePay(HourlyPay, HoursPerShift, calc);
BTW, local variables, as well as methods parameters, should be CamelCased.

declaring new objects with GUI in C#

So I am using a GUI with a class. I have done it before and I know most of the time you create an event for a button. Then when that button is pushed, you can create a new object. In this project I am working on, I have a TextBox that I type a name and a score into. Then when I hit the enter button that I have, I want to create a new object with the parameterized constructor and place the name and score in different arrays so I can manipulate them. Then I want to produce the highest, lowest, and avg scores. I have had previous projects where I just create a new object when the button is pressed. But with this I am loading in multiple things in the same TextBox. So every time the button was hit I was creating a new object. What I want to do is create the object once with a parameterized constructor and then add the names and scores to arrays within the class. Any suggestions.
The bottom method in my form class I tried to mess around and do it this way, but it wouldn't do anything.
private void nameTextBox_TextChanged(object sender, EventArgs e)
{
//Get the information from the text box and store it in a variable
string userInput = nameTextBox.Text;
//Create a new object with the parameterized constructor
myBowlingTeam = new BowlingTeam(userInput);
}
PLEASE HELP. This is like my only hiccup. If I get this part to work right the program will work. Cause I know how to work with the class to produce the results I want. Thanks in advance.
Here is my class code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Project_9
{
class BowlingTeam
{
const int MAX = 10;
//local variables
int sizeOfName = 0;
int sizeOfScore = 0;
//Declare Private Data Members
private string nameAndScore = "";
private string name = "";
private int score = 0;
private string[] nameArray = new string[MAX];
private int[] scoreArray = new int[MAX];
private string[] nameAndScoreArray = new string[MAX];
//Default Constructor
//Purpose: To set the initial values of an object
//Parameters: None
//Returns: Nothing
public BowlingTeam()
{
nameAndScore = "";
name = "";
score = 0;
for(int i = 0; i < MAX; i++)
{
nameArray[i] = "";
}
for(int i = 0; i < MAX; i++)
{
scoreArray[i] = 0;
}
for (int i = 0; i < MAX; i++)
{
nameAndScoreArray[i] = "";
}
}
//Parameterized Constructor
//Purpose: To set the values of an object
//Parameters: None
//Returns: Nothing
public BowlingTeam(string aString)
{
nameAndScore = aString;
name = "";
score = 0;
for (int i = 0; i < MAX; i++)
{
nameArray[i] = "";
}
for (int i = 0; i < MAX; i++)
{
scoreArray[i] = 0;
}
for (int i = 0; i < MAX; i++)
{
nameAndScoreArray[i] = "";
}
}
//Split the Input Method
//Purpose: To Split up the data in the array
//Parameters: An array of strings
//Returns: Nothing
public void SplitAndDisperseArray()
{
nameAndScoreArray = nameAndScore.Split();
name = nameAndScoreArray[0];
score = int.Parse(nameAndScoreArray[1]);
//Place the name and the score in their one arrays
PlaceInNameArray(name);
PlaceInScoreArray(score);
}
//Find Highest Score Method
//Purpose: To find the highest score
//Parameters: An array of int
//Returns: An int
public int CalcHighestScore()
{
int highestScore = 0;
int size = 0;
for (int i = 0; i < MAX; i++ )
{
if (scoreArray[i] < scoreArray[i + 1])
{
highestScore = scoreArray[i];
}
else
{
highestScore = scoreArray[i + 1];
}
}
return highestScore;
}
//Find Lowest Score Method
//Purpose: To find the lowest score
//Parameters: An array of int
//Returns: An int
public int CalcLowestScore(int[] anArrayOfInts, int sizeOfArray)
{
int lowestScore = 0;
while (sizeOfArray < MAX)
{
if (anArrayOfInts[sizeOfArray] < anArrayOfInts[sizeOfArray + 1])
{
lowestScore = anArrayOfInts[sizeOfArray];
}
else
{
lowestScore = anArrayOfInts[sizeOfArray + 1];
}
}
return lowestScore;
}
//Calulate Avg. Score Method
//Purpose: To calculate the avg score
//Parameters: An array of int
//Returns: An double
public double CalculateAvgScore(int[] anArrayOfInts, int sizeOfArray)
{
int sum = 0;
double avg = 0;
//Add up all of the elements in the array
while(sizeOfArray < MAX)
{
sum += anArrayOfInts[sizeOfArray];
}
//Divide the sum by the size of the array
return avg /= sum;
}
//Set Score Array Method
//Purpose: To put scores in the score array
//Parameters: An int
//Returns: Nothing
public void PlaceInScoreArray(int aScore)
{
scoreArray[sizeOfScore] = score;
sizeOfScore++;
}
//Set Name Array Method
//Purpose: To put names in the names array
//Parameters: A string
//Returns: Nothing
public void PlaceInNameArray(string aName)
{
nameArray[sizeOfName] = name;
sizeOfName++;
}
}
}
Here is my Form1 code for the GUI:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Project_9
{
public partial class Form1 : Form
{
//Declare a reference variable to the class
private BowlingTeam myBowlingTeam;
public Form1()
{
InitializeComponent();
myBowlingTeam = new BowlingTeam();//Create a BowlingTeam object with the default constructor
}
//ExitToolStripMenuItem1_Click
//Purpose: To close the application when clicked
//Parameters: The sending object and the event arguments
//Returns: nothing
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
//AboutToolStripMenuItem1_Click
//Purpose: To display student information
//Parameters: The sending object and the event arguments
//Returns: nothing
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("Charlie Barber\nCS 1400-X01\nProject 9");
}
//Enter Button Clicked
//Purpose: To store the info in an array when the button is pressed
//Parameters: The sending object and the event arguments
//Returns: nothing
private void button1_Click(object sender, EventArgs e)
{
//Get the information from the text box and store it in a variable
string userInput = nameTextBox.Text;
if (userInput != "")
{
//Create a new object with the parameterized constructor
// myBowlingTeam = new BowlingTeam(userInput);
//Split the string into two separte pieces of data
myBowlingTeam.SplitAndDisperseArray();
//Clear the text box
nameTextBox.Clear();
}
else
{
int highestScore = myBowlingTeam.CalcHighestScore();
}
}
//Nothing
private void nameTextBox_TextChanged(object sender, EventArgs e)
{
//Get the information from the text box and store it in a variable
string userInput = nameTextBox.Text;
//Create a new object with the parameterized constructor
myBowlingTeam = new BowlingTeam(userInput);
}
}
What is stopping you from using a class for the players inside the team? Keep the arrays synchronised in your solution seems more trouble than its worth.
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace Observable
{
class BowlingTeam
{
public string TeamName { get; set; }
private readonly IList<Player> players = new ObservableCollection<Player>();
public IList<Player> Players
{
get
{
return players;
}
}
public void AddPlayer(string name, int score)
{
AddPlayer(new Player(name, score));
}
public void AddPlayer(Player p)
{
players.Add(p);
}
public Player HighestRanked()
{
if (Players.Count == 0)
{
// no players
return null;
}
int max = 0, index = -1;
for (int i = 0; i < Players.Count; i++)
{
if (Players[i].Score > max)
{
index = i;
max = Players[i].Score;
}
}
if (index < 0)
{
// no players found with a score greater than 0
return null;
}
return Players[index];
}
public BowlingTeam()
{
}
public BowlingTeam(string teamName)
{
this.TeamName = teamName;
}
}
class Player
{
public string Name { get; set; }
public int Score { get; set; }
public Player()
{
}
public Player(string name, int score)
{
this.Name = name;
this.Score = score;
}
public override string ToString()
{
return string.Format("{0} {1:n2}", Name, Score);
}
}
}
which could be manipulated as such
BowlingTeam b1 = new BowlingTeam("SO");
b1.AddPlayer("Player 1", 100);
b1.AddPlayer("Player 2", 135);
b1.AddPlayer("Player 3", 90);
b1.AddPlayer("Player 4", 127);
Console.WriteLine("Highest ranked player: {0}", b1.HighestRanked());
An advantage for later is that you can hang on the OnCollectionChangedEvents of your players, to be notified when players were added/removed.

C# Comparing List objects to passed parameters

What I am trying to do is get the number of right angled triangles between 1 and 20 on both sides.
Most of the logic is fine, but when I want to check for 3, 4 and 5 this is one triangle, while 4, 3 and 5 would not be valid as it 3, 4, 5 in a different order.
Here is the code that I have written for the problem area
public bool isAlreadyValidTriangle(int intAdj, int intOpp, List<Triangle> triangleList)
{
bool breakLoop = false;
Int32 length = triangleList.Count;
for (int index = 0; index < length && breakLoop != false; index++)
{
//This is to compare an existing adjacent that is stored in the list to the
//supplied opposite, this is to prebent the 3, 4, 5 and 4, 3, 5 issue
var response = triangleList.Find(r => r.IntAdjacent == intOpp);
if (response !=null)
{
//This is to compare an existing opposite that is stored in the list to the
//supplied adjacent, this is to prebent the 3, 4, 5 and 4, 3, 5 issue
var otherResponse = triangleList.Find(r => r.IntOpposite == intAdj);
if (otherResponse != null)
{
breakLoop = true;
}
}
}
return breakLoop;
}
Just in case anybody needs the Triangle code, here it is
public class Triangle
{
private int intAdjacent;
private int intOpposite;
private int intHypotenuse;
public Triangle(int intAdjacent, int intOpposite, int intHypotenuse)
{
this.intAdjacent = intAdjacent;
this.intOpposite = intOpposite;
this.intHypotenuse = intHypotenuse;
}
public int IntAdjacent
{
get { return intAdjacent; }
}
public int IntOpposite
{
get { return intOpposite; }
}
public int IntHypotenuse
{
get { return intHypotenuse; }
}
}
Could some one spot to see where I am making a mistake in the logic or have made an error in the code itself?
Keith
You can simplify this quite a lot like this:
public bool isAlreadyValidTriangle(int intAdj, int intOpp, List<Triangle> triangleList)
{
if(triangleList.Any(t => t.IntAdjacent == intAdj && t.IntOpposite == intOpp))
return true;
return triangleList.Any(t => t.IntAdjacent == intOpp && t.IntOpposite == intAdj);
}
It first looks for any matches where the passed in values are a match, then reverses the search if they don't. It's slightly different to your code in that it looks for both adjacent and opposite at the same time which is where you went wrong. Additionally, it uses Any which returns a boolean value if any item is found that matches.
Thinking about this further, I would change the function to make it an extension method like this:
public static bool isAlreadyValidTriangle(this List<Triangle> triangleList, int intAdj, int intOpp)
{
if(triangleList.Any(t => t.IntAdjacent == intAdj && t.IntOpposite == intOpp))
return true;
return triangleList.Any(t => t.IntAdjacent == intOpp && t.IntOpposite == intAdj);
}
This means you can call it with a little more readability:
List<Triangle> triangleList = new List<Triangle>();
... fill list with triangles ...
if(triangleList.isAlreadyValidTriangle(adjacent, opposite)
{
...
}
First of all thanks for the advice and help.
Here is the complete code from start to finish
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
namespace ConsoleApplication1
{
public class Program
{
private static double doubleHypotenuse = 0;
private static int adjacent = 1;
private static int opposite = 1;
private static int limit = 200;
private static int count = 0;
public static void Main(string[] args)
{
TriangleLogic triLogic = new TriangleLogic();
List<Triangle> triangleList = new List<Triangle>();
List<Triangle> trianglePlus1 = new List<Triangle>();
while (adjacent < limit)
{
opposite = 1;
while (opposite < limit)
{
doubleHypotenuse = triLogic.intRightAngle(adjacent, opposite);
if (doubleHypotenuse % 1 == 0)
{
if (!triLogic.isAlreadyValidTriangle(adjacent, opposite, triangleList))
{
triangleList.Add(new Triangle(adjacent, opposite, (int)Convert.ToInt32(doubleHypotenuse)));
}
count++;
}
opposite++;
}
adjacent++;
}
Console.WriteLine("The following are integer triangles");
triangleList.ForEach(delegate(Triangle pytag)
{
if ((pytag.IntHypotenuse - pytag.IntOpposite) == 1)
{
trianglePlus1.Add(new Triangle(pytag.IntAdjacent, pytag.IntOpposite, pytag.IntHypotenuse));
}
Console.WriteLine(pytag.IntAdjacent + ", " + pytag.IntOpposite + " and " + pytag.IntHypotenuse);
});
Console.WriteLine("the number of squares is " + count);
Int32 length = triangleList.Count;
Console.WriteLine("the length of the list is " + length);
Console.WriteLine("");
Console.WriteLine("the List of triangles with the hypotenuse 1 ");
Console.WriteLine("more than the opposite");
trianglePlus1.ForEach(delegate(Triangle pytagPlus1)
{
Console.WriteLine(pytagPlus1.IntAdjacent + ", " + pytagPlus1.IntOpposite + " and " + pytagPlus1.IntHypotenuse);
});
Int32 lengthPlus1 = trianglePlus1.Count;
Console.WriteLine("the length of the list is " + lengthPlus1);
}
}
}
Here is the Triangle Class
public class Triangle
{
private int intAdjacent;
private int intOpposite;
private int intHypotenuse;
public Triangle(int intAdjacent, int intOpposite, int intHypotenuse)
{
this.intAdjacent = intAdjacent;
this.intOpposite = intOpposite;
this.intHypotenuse = intHypotenuse;
}
public int IntAdjacent
{
get { return intAdjacent; }
}
public int IntOpposite
{
get { return intOpposite; }
}
public int IntHypotenuse
{
get { return intHypotenuse; }
}
}
And finally the TriangleLogic class
public class TriangleLogic
{
private double squareAdjacent = 0;
private double squareOpposite = 0;
private double squareSum = 0;
public TriangleLogic()
{
}
public double intRightAngle(int intAdjacent, int intOpposite)
{
squareAdjacent = Math.Pow(Convert.ToDouble(intAdjacent), 2);
squareOpposite = Math.Pow(Convert.ToDouble(intOpposite), 2);
squareSum = squareAdjacent + squareOpposite;
return Math.Sqrt(squareSum);
}
public bool isAlreadyValidTriangle(int intAdj, int intOpp, List<Triangle> triangleList)
{
if (triangleList.Any(t => t.IntAdjacent == intAdj && t.IntOpposite == intOpp))
return true;
return triangleList.Any(t => t.IntAdjacent == intOpp && t.IntOpposite == intAdj);
}
}
Thanks again for the support

Categories

Resources