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 1 year ago.
Improve this question
I'm having trouble and I was wondering if there is something wrong with my code.
The code should execute the following
When executed within the terminal the MoveAmount and Move should end up equal to each other.
Side A should follow the equation
(x*a)/(a+b) and execute with the correct value. (x representing the move and A and B representing their perspective ratio).
Move - SideA = Side B
Move = SideA + SideB
Unfortunately it doesn't seem to be working and I am unable to get the code to create the proper output.
If I try to input my values based on this graph the Calculated Movement of Side A and B return incorrectly and the output does not follow the desired perameters above.
If anyone can give me any tips let me know.
using System;
namespace Example
{
class CalculatedMove
{
public double Move = 0.0;
public double SideARatio = 0.0;
public double SideBRatio = 0.0;
public CalculatedMove(double SideARatio, double SideBRatio, double Move)
{
this.Move = Move;
this.SideARatio = SideARatio;
this.SideBRatio = SideBRatio;
}
public virtual void SideA()
{
double SideA = 0.0;
SideA = (Move * SideARatio) /(SideARatio + SideBRatio);
Console.WriteLine("Calculated Side A Movement is {00:00.0000}", SideA);
}
public void SideB()
{
double SideB = 0.0;
SideB = Move - SideARatio;
Console.WriteLine("The Calculated Side B Movement is {00:00.0000}", SideB);
}
public void MovementAmount()
{
double MovementAmount = 0.0;
MovementAmount = SideARatio + SideBRatio;
Console.WriteLine("The Calculated Move Amount is {0:00.0000}", MovementAmount);
}
}
class Program
{
static void Main(string[] args)
{
double Move, SideARatio, SideBRatio = 0.0;
Console.WriteLine("Enter the Move Amount ");
Move = Double.Parse(Console.ReadLine());
Console.WriteLine("Side A Ratio");
SideARatio = Double.Parse(Console.ReadLine());
Console.WriteLine("Side B Ratio");
SideBRatio = Double.Parse(Console.ReadLine());
CalculatedMove objMove = new CalculatedMove(Move, SideARatio,SideBRatio);
objMove.SideA();
objMove.SideB();
objMove.MovementAmount();
Console.Read();
}
}
}
First of all, as JohnG said, the sequence of parameters is wrong when calling parameters.
Then when calculating SideB, SideARatio should not be subtracted, but SideA should be subtracted.
Finally, Move should be SideA+SideB, not SideARatio+SideBRatio.
using System;
namespace Example {
class CalculatedMove {
private double move =0.0;
public double Move {
get { return move; }
set { move=value; }
}
private double sideARatio=0.0;
public double SideARatio {
get { return sideARatio; }
set { sideARatio=value; }
}
private double sideBRatio = 0.0;
public double SideBRatio {
get { return sideBRatio; }
set { sideBRatio=value; }
}
private double sideA = 0.0;
public double SideA {
get { return sideA; }
set { sideA=value; }
}
private double sideB = 0.0;
public double SideB {
get { return sideB; }
set { sideB=value; }
}
private double movementAmount = 0.0;
public double MovementAmount {
get { return movementAmount; }
set { MovementAmount=value; }
}
public CalculatedMove(double SideARatio, double SideBRatio, double Move) {
this.move=Move;
this.sideARatio=SideARatio;
this.sideBRatio=SideBRatio;
}
public virtual void SideAMove() {
SideA=(Move*SideARatio)/(SideARatio+SideBRatio);
Console.WriteLine("Calculated Side A Movement is {00:00.0000}", SideA);
}
public void SideBMove() {
SideB=(Move*SideBRatio)/(SideARatio+SideBRatio);
Console.WriteLine("The Calculated Side B Movement is {00:00.0000}", SideB);
}
public void MovementAmountMove() {
MovementAmount=SideA+SideB;
Console.WriteLine("The Calculated Move Amount is {0:00.0000}", MovementAmount);
}
}
class Program {
static void Main(string[] args) {
double Move, SideARatio, SideBRatio = 0.0;
Console.WriteLine("Enter the Move Amount ");
Move=Double.Parse(Console.ReadLine());
Console.WriteLine("Side A Ratio");
SideARatio=Double.Parse(Console.ReadLine());
Console.WriteLine("Side B Ratio");
SideBRatio=Double.Parse(Console.ReadLine());
CalculatedMove objMove = new CalculatedMove( SideARatio, SideBRatio,Move);
objMove.SideAMove();
objMove.SideBMove();
objMove.MovementAmountMove();
Console.Read();
}
}
}
Output:
As 3.Move - SideA = Side B :
public void SideB()
{
double SideB = 0.0;
SideB = Move - SideARatio; // Here is the problem;
Console.WriteLine("The Calculated Side B Movement is {00:00.0000}", SideB);
}
Fix public void SideB()
public void SideB()
{
double SideB = 0.0;
SideB = (Move * SideBRatio) /(SideARatio + SideBRatio);
Console.WriteLine("The Calculated Side B Movement is {00:00.0000}", SideB);
}
Related
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();
}
I want to create a Compound Interest Calculator in C# using two classes in different namespaces but can't for the life of me figure out why I keep getting errors.
PSA I am a beginner, I know this code probably looks awful, but please be kind.
Here is CompoundTest.cs
namespace CompoundTest
{
class Program
{
static void Main(string[] args)
{
CompoundClass newprogram = new CompoundClass();
Console.Write("\nPlease enter the initial balance for your account: ");
double balance = Convert.ToDouble(Console.ReadLine());
Console.Write("\nPlease enter the annual interest rate: ");
double interestRate = Convert.ToDouble(Console.ReadLine()) / 100;
Console.Write("\nHow many years will you acrue interest? ");
double annualAmount = Convert.ToDouble(Console.ReadLine());
Console.WriteLine($"Your balance after {annualAmount} years is {accountBalance:C}");
Console.ReadLine();
}
}
}
And here is Compound.cs
using System;
namespace Compound
{
public class CompoundClass
{
private double balance;
public int value { get; private set; }
public CompoundClass()
{
Balance = value;
}
public double Balance
{
get
{
return balance;
}
private set
{
if (value > 0)
{
balance = value;
}
}
}
public void Rate(double interestRate)
{
interestRate = value / 100;
}
public void Years(double annualAmount)
{
annualAmount = value * 12;
}
public void addMethod(double accountBalance)
{
for (int i = 1; i < annualAmount + 1; i++)
{
accountBalance = balance * Math.Pow(1 + interestRate / annualAmount, annualAmount * i);
}
}
}
}
I get the error:
CS0103 C# The name '..' does not exist in the current context - in the public void addMethod(double accountBalance) method
You are not storing any data on the CompoundClass, the method
public void Rate(double interestRate)
{
interestRate = value / 100;
}
only operates on the input parameter interestrate inside the functions scope, after that the result of the calculation is lost
If you want to reuse a variable on the entire lifetime of the CompoundClass, then define it as a member variable like:
private double _interestRate
and change your function to
public void Rate()
{
_interestRate = value / 100;
}
and for the annualAmount as well
private double _annualAmount;
public void Years()
{
_annualAmount = value * 12;
}
and your calculation to
public double addMethod(double accountBalance)
{
for (int i = 1; i < annualAmount + 1; i++)
{
accountBalance = balance * Math.Pow(1 + _interestRate / _annualAmount, _annualAmount * i);
}
return accountBalance;
}
There is more then one thing wrong with this code. And I am honestly not sure if I even got anything close to your problem yet.
using System;
namespace Compound
{
public class CompoundClass
{
private double balance;
public int value { get; private set; }
public CompoundClass()
{
//Balance with a big B is nowhere in context
Balance = value;
}
public double Balance
{
get
{
return balance;
}
private set
{
if (value > 0)
{
balance = value;
}
}
}
//As remarked by somebody else, this function does nothing. Without return or out parameter, interest rate will stay at nothing.
public void Rate(double interestRate)
{
interestRate = value / 100;
}
//The naming of this variable is bad. Did you mean "Amoung of Months"?
//Also as someone else pointed out, you do not return or otherwise persist this value
public void Years(double annualAmount)
{
annualAmount = value * 12;
}
//Method does not return anything.
//accountBalance is a local value and will not persist
public void addMethod(double accountBalance)
{
for (int i = 1; i < annualAmount + 1; i++)
{
//Avoid putting that much stuff into 1 line. It really messes with your ability to debug
//1-2 operations + 1 assignment to a temporary variable per line
//Anything more and you will have serious issues debugging this
accountBalance = balance * Math.Pow(1 + interestRate / annualAmount, annualAmount * i);
}
}
}
}
Generally the variables this works with should be either purely parameters (wich means it should be a static class with static functions) or mostly class variables. You have both things mixed all over the place.
I have a C# project for school. I am unable to move my character in this ASCII console game. It has to be OO. After I run the code I get this:
After I press left or right I get
Can someone help me on this? Any help is appreciated.
program.cs:
class Program
{
static void Main(string[] args)
{
SuperConsole.Init(50, 44);
// create the game
Game game = new Game(30, 30);
//create objects
Entity spaceship = new Entity(1, 15, '#', SuperConsoleColor.Cyan);
// start the game loop
RunGameLoop(game);
}
protected static void RunGameLoop(Game game)
{
SuperConsole.BackgroundColor = SuperConsoleColor.DarkBlue;
SuperConsole.ForegroundColor = SuperConsoleColor.Gray;
int refreshRate = 20;
SuperConsole.CursorVisible = false;
SuperConsole.BackgroundColor = SuperConsoleColor.DarkBlue;
SuperConsole.ForegroundColor = SuperConsoleColor.Gray;
SuperConsole.Clear();
Reset(game);
game.Draw(0.0f);
SuperConsole.Flush();
/*
SuperConsole.SetCursorPosition(0, 0);*/
while (true)
{
while (SuperConsole.KeyAvailable)
{
ConsoleKeyInfo key = SuperConsole.ReadKey(true);
game.OnInput(key.Key);
}
System.Threading.Thread.Sleep(1000 / refreshRate);
Reset(game);
game.Draw(1.0f / (float)refreshRate);
SuperConsole.Flush();
}
}
protected static void Reset(Game game)
{
SuperConsole.BackgroundColor = SuperConsoleColor.Black;
SuperConsole.ForegroundColor = SuperConsoleColor.Black;
SuperConsole.SetCursorPosition(0, 0);
for (int y = 0; y < game.GetHeight(); ++y)
{
for (int x = 0; x < game.GetWidth(); ++x)
{
SuperConsole.Write(" ");
}
SuperConsole.WriteLine();
}
SuperConsole.SetCursorPosition(0, 0);
}
}
}
game.cs:
class Game : Entity
{
protected int width, height;
Entity spaceship = new Entity(1, 15, '#', SuperConsoleColor.Cyan);
public Game(int newWidth, int newHeight)
{
// set the size
width = newWidth;
height = newHeight;
// set the window
Console.WindowWidth = width+1;
Console.WindowHeight = height+1;
}
public int GetWidth()
{
return width;
}
public int GetHeight()
{
return height;
}
public void Draw(float dt)
{
SuperConsole.SetCursorPosition(spaceship.GetX(), spaceship.GetY());
SuperConsole.ForegroundColor = spaceship.GetColour();
SuperConsole.Write(spaceship.GetChar());
}
public void OnInput(ConsoleKey key)
{
int redo = 0;
ConsoleKey pressedKey = key;
do
{
Console.Clear();
switch (pressedKey)
{
case ConsoleKey.LeftArrow:
SuperConsole.SetCursorPosition(spaceship.GetX() - 1, spaceship.GetY());
break;
case ConsoleKey.UpArrow:
break;
case ConsoleKey.RightArrow:
SuperConsole.SetCursorPosition(spaceship.GetX()+1, spaceship.GetY());
break;
case ConsoleKey.DownArrow:
break;
}
} while (redo == 0);
}
}
}
entity.cs:
class Entity
{
protected int xPos;
protected int yPos;
protected char character;
protected SuperConsoleColor colour;
public Entity()
{
}
public Entity(int xPosNew, int yPosNew, char newCharacter, SuperConsoleColor newColour)
{
//define position
xPos = xPosNew;
yPos = yPosNew;
//define character
character = newCharacter;
//define colour
colour = newColour;
}
public char GetChar()
{
return character;
}
public int GetX()
{
return xPos;
}
public int GetY()
{
return yPos;
}
public SuperConsoleColor GetColour()
{
return colour;
}
}
}
I see two issues:
Within RunGameLoop(Game game) you should replace while (SuperConsole.KeyAvailable) with if (SuperConsole.KeyAvailable).
Within Game.OnInput(ConsoleKey) you change the cursor position instead of the spaceship position
Also try using breakpoints to Check if the code reaches Game.Draw() and check if the spaceship position and the cursor position are correct.
Also you should get a bit more into C#.
Instead of
public char GetChar()
{
return character;
}
private character;
.Net allows you to use Properties:
public char Character
{
get; private set;
}
or
public char Character
{
get { return character; }
}
private character = '#';
Hope this helps.
Apart from that: No offense, but this question isn't really what Stackoverflow is for. In future, please be more patient and try to googling debugging tips instead of letting Stackoverflow do the 'dirty work' for you.
I wrote a C# program to print the area, but when I run the program it always prints "The area is 0". Any idea what seems to be the problem?
class Circle
{
double radius;
// int color;
double area;
public void setCircleInfo()
{
radius = 15;
//color = 225;
}
public void calculateArea()
{
area = 3.142 * radius * radius;
}
public double getRadius()
{
return radius;
}
public void displayArea()
{
Console.WriteLine("The area is " + area.ToString());
Console.ReadLine();
}
}
}
Here's the code to the main method:
{
class Program
{
static void Main(string[] args)
{
Circle obj1 = new Circle();
obj1.displayArea();
}
}
}
Your code runs fine for me. The reason why you are always getting The area is 0 is probably you are missing any one of the following calls. Note that If you miss setCircleInfo or calculateArea, you will get a zero as the result.
Circle c = new Circle();
c.setCircleInfo();
c.calculateArea();
c.displayArea();
Hope this helps :-)
I would adjust the object a little bit to make it easier to use:
class Circle
{
public double Radius
{
get;
set;
}
public double Area
{
get
{
return 3.142 * radius * radius;
}
}
public Circle(double radius)
{
Radius = radius;
}
public void displayArea()
{
Console.WriteLine("The area is " + Area.ToString());
Console.ReadLine();
}
}
You can then use it like this:
static void Main(string[] args)
{
Circle obj1 = new Circle(15);
obj1.displayArea();
}
Change your code
static void Main(string[] args)
{
Circle obj1 = new Circle();
obj1.setCircleInfo();
obj1.calculateArea();
obj1.displayArea();
}
add in your Circle constructor method:
public Circle(double radius){
this.radius=radius;
c.setCircleInfo();
c.calculateArea();
c.displayArea();
}
I have write a code to calculate the area of different shapes using polymorphism (Virtua & Override Method) but not getting correct result. :(
Below is my code:
class Program
{
static void Main(string[] args)
{
double side = 0;
double length = 0;
double width = 0;
double height = 0;
double baseoftriangle = 0;
double radius = 0;
UserChoice:
Console.WriteLine("For what shape you want to calculate the Area:\n1. Sqaure\n2. Rectangle\n3. Triangle\n4. Circle");
Console.Write("Please Select the number from above options: ");
int choice = int.Parse(Console.ReadLine());
switch (choice)
{
case 1:
Console.Write("Please enter the side of square: ");
side = double.Parse(Console.ReadLine());
break;
case 2:
Console.Write("Please enter the length of rectangle: ");
length = double.Parse(Console.ReadLine());
Console.Write("Please enter the width of rectangle: ");
width = double.Parse(Console.ReadLine());
break;
case 3:
Console.Write("Please enter the height of triangle: ");
height = double.Parse(Console.ReadLine());
Console.Write("Please enter the base of triangle: ");
baseoftriangle = double.Parse(Console.ReadLine());
break;
case 4:
Console.Write("Please enter the radius of circle: ");
radius = double.Parse(Console.ReadLine());
break;
default:
Console.WriteLine("Incorrect Choice, please try again!");
goto UserChoice;
}
CalculateArea Sqa = new Square();
Sqa = new Rectangle();
Sqa = new Triangle();
Sqa = new Circle();
if (choice == 1)
{
Sqa.Area(side);
Sqa.ShowResult();
}
else if(choice==2)
{
Sqa.Area(length,width);
Sqa.ShowResult();
}
else if(choice==3)
{
Sqa.Area(height, baseoftriangle);
Sqa.ShowResult();
}
else
{
Sqa.Area(radius);
Sqa.ShowResult();
}
ChoiceOfAnotherCalculation:
Console.Write("\nDo you want to calculate area of any other shape? Give input in Yes or NO: ");
string choice1 = Console.ReadLine();
switch (choice1.ToUpper())
{
case "YES":
goto UserChoice;
case "NO":
break;
default:
Console.WriteLine("Incorrect Choice, please try again!");
goto ChoiceOfAnotherCalculation;
}
}
}
class CalculateArea
{
public double result;
public virtual void Area(double side)
{
}
public virtual void Area(double length, double width)
{
}
public void ShowResult()
{
Console.WriteLine($"Your Result is {result}");
}
}
class Square: CalculateArea
{
public override void Area(double side)
{
result = side * side;
}
}
class Rectangle:CalculateArea
{
public override void Area(double length, double width)
{
result = length * width;
}
}
class Triangle:CalculateArea
{
public override void Area(double height, double baseoftriangle)
{
result = (height * baseoftriangle)/2;
}
}
class Circle:CalculateArea
{
public override void Area(double radius)
{
result = 3.14159 * radius * radius;
}
}
For Rectangle & Triangle, I am always getting 0 as a result and for square I am getting result from circle. I think this issue is causing because of the way I have created objects for class (May be because of lack of understanding in polymorphism).
Can someone please have a look and let me know what is the actual problem here.
Apart from this also I would appreciate your efforts if you can provide me the solution with get & set properties for each class. I have tried to write the code (Where I have tried to define the property in each derive class as well as in base class) but was getting various errors that's why I have jump on above solution.
I will also request please do not downvote the question as system won't allow me ask question for a long time. As this is the only platform where I can understood the things properly.
Many Thanks.
Inside the switch statement, after case 1, your program will exit. This is because you have used return;, you might have intended to use break; instead. Break statement ensures that your switch wont fall through to the next statement, and a return statement would terminate the execution immediately.
Correct case statement should be like this
case 1:
Console.Write("Please enter the side of square: ");
side = int.Parse(Console.ReadLine());
break;
EDIT
Base class will only hold an abstract method to calculate area, which should be implemented by inheriting classes.
public abstract class Shape
{
// must implement by inheriting classes
public abstract double CalculateArea();
}
Each shape would calculate area using different parameters, therefore you should create properties that would be required by that specific shape.
public class Square : Shape
{
// properties differ based on the shape..
// eg: triangle needs height and base
// edit CalculateArea method based on the shape
public double Length { get; set; }
public override double CalculateArea()
{
return Length * Length;
}
}
Implement just like you did before, create an instance of the shape then pass the required parameters and invoke CalculateArea() method, that would return a double value:
double length;
Console.WriteLine("Enter length of one side: ");
if (!double.TryParse(Console.ReadLine(), out length))
Console.WriteLine("Invalid value, must be a number or decimal value.");
Square sq = new Square();
sq.Length = length;
Console.WriteLine(sq.CalculateArea().ToString("F"));
For polymorphism your classes should look like this:
abstract class Shape
{
public abstract double Area {get;}
}
class Square: Shape
{
public double Side {get;}
public override double Area => Side * Side;
public Square (double side)
{
this.Side = side;
}
}
class Rectangle:Shape
{
public double Width {get;}
public double Length {get;}
public override double Area => Width * Length;
public Rectangle (double width, double length)
{
this.Width = width;
this.Length = length;
}
}
etc.
With this in place, you can create the Shape once during the first case statement and can then use the .Area property on it in your output.
You should not have code to do output in your shape class, keep each class focused on one thing (SRP).
Your shapes should track their own properties because you may later want to add, say, a 'Description' property that uses those properties to describe the shape.