I've created a program which should calculate the surface area of an irregular shaped object, such as a lake.
I read in a file, which contained the values for the x and y values, and the depth.
I'm new to C#, and so I don't fully understand everything yet, but I think my code should work, however, it doesn't seem to be writing the value for the area onto the screen.
I know that Console.WriteLine(_surface); SHOULD work , but it I can't seem to get it to do anything, and it's probably in the wrong place!
Can someone please tell me where I'm going wrong?
My code is as follows.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using NUnit.Framework;
namespace ConsoleApplication1
{
public class ValueXyz
{
public double X { get; set; }
public double Y { get; set; }
public int Z { get; set; }
}
public class SurfaceCalculator
{
private ValueXyz[] _valuesXyz;
private double _surface;
private readonly string _textWithValues;
public SurfaceCalculator(string textWithValues)
{
_textWithValues = textWithValues;
SetValuesToCalculate();
}
public double Surface
{
get { return _surface; }
}
public void CalculateSurface()
{
for (var i = 0; i < _valuesXyz.Length; i++)
{
if (_valuesXyz[i].Z == 0)
_surface = (_valuesXyz[i].X * _valuesXyz[i + 1].Y) - (_valuesXyz[i + 1].X * _valuesXyz[i].Y);
Console.WriteLine(_surface);
}
}
private void SetValuesToCalculate()
{
var valuesXyz = _textWithValues.Split(' ');
_valuesXyz = valuesXyz.Select(item => new ValueXyz
{
X = Convert.ToDouble(item.Split(',')[0]),
Y = Convert.ToDouble(item.Split(',')[1]),
Z = Convert.ToInt32(item.Split(',')[2])
}).ToArray();
}
public void TestSurfaceCalculatorGetsAValue()
{
var textWithValues = File.ReadAllLines(#"C:\Users\user\Documents\Visual Studio 2010\Projects\Lake_Take_Toooooo\Lake_Take_Toooooo\bin\Debug\Lake_Test.csv");
var calculator = new SurfaceCalculator(_textWithValues);
calculator.CalculateSurface();
Assert.IsNotNull(calculator.Surface);
}
static void Main()
{
Console.ReadKey();
}
}
}
This is my first time using classes, so apologies if there's an obvious answer.
Thanks for your help!
You need to actually call the method inside the Main method, which is the program entry point. Like:
static void Main()
{
CalculateSurface();
Console.ReadKey();
}
When you run your program, only the code inside the Main method is actually executed. If you do not call anything from there then no code is executed.
No function is being called in the Main event...
I should imagine read key will wait for key input then close, correct?
Are you trying to run this as console application or as unit test? (It looks like you're trying to run it as unit test since you're using NUnit.Framework and there is a Test-method with an Assert...)
If you want to run it as console application, you have to call the code that should get executed in the Main method.
If you want to run it as unit test, you have to add some "attributes" to your test class and test method. The class should have the [TestFixture] attribute, and the method should have the [Test] attribute, like:
[TestFixture]
public class SurfaceCalculator {
...
[Test]
public void TestSurfaceCalculatorGetsAValue() {
...
}
}
Related
I am making a basic shop system includes car name, price and buyable. I am saving data to a text file. When I replay, I can't get the last variables I've changed. But, if I refresh at Editor by CTRL+R and start the game, variables are loading correct. What am I doing wrong? I am new at storage and JSON issues. Thanks for answers...
Here is the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System;
public class GameHandler : MonoBehaviour
{
[Serializable]
public class Car
{
public string name;
public int price;
public bool unlocked;
}
[Serializable]
public class CarList{
public Car[] cars;
}
private Car cars = new Car();
public CarList myCars = new CarList();
//-------
public int chosenCar;
//-------
public TextAsset CARS;
//-------
private void Start() {
GetFromJSON();
}
private void Update() {
if(Input.GetKeyDown(KeyCode.L))
GetFromJSON();
if(Input.GetKeyDown(KeyCode.S))
SaveToJSON();
}
public void ChangeCarIndex(int a){
chosenCar = a;
}
//This is a button func.
public void ChangePrice(int a){
myCars.cars[chosenCar].price = a;
SaveToJSON();
}
public void GetCarName(){
Debug.Log(myCars.cars[chosenCar].name);
}
public void GetCarPrice(){
Debug.Log(myCars.cars[chosenCar].price);
}
public void SaveToJSON(){
string jsOutput = JsonUtility.ToJson(myCars);
File.WriteAllText(Application.dataPath + "/CARS.txt", jsOutput);
Debug.Log("SaveToJSON() called");
}
public void GetFromJSON(){
myCars = JsonUtility.FromJson<CarList>(CARS.text);
Debug.Log("GetFromJSON() called");
}
}
When running this in the editor try to add
public void SaveToJSON()
{
string jsOutput = JsonUtility.ToJson(myCars);
File.WriteAllText(Application.dataPath + "/CARS.txt", jsOutput);
Debug.Log("SaveToJSON() called");
#if UNITY_EDITOR
UnityEditor.AssetDatabase.Refresh();
#endif
}
Though actually this isn't really necessary! Afaik you could also simply set the text of the textasset:
public void SaveToJSON()
{
string jsOutput = JsonUtility.ToJson(myCars);
CARS.text = jsOutput;
Debug.Log("SaveToJSON() called");
}
BUT NOTE:
in general note that this makes only sense in the editor itself.
If you target to do this in an actually later built application you would rather go via a file in Application.persistentDataPath. Problem with that though: The data can easily be seen and edited by the user. So if this is anything sensitive you will need to go for a central database server with user login.
A quick brief of the program that i have already done.
Golfer: A Golfer can be equipped with a Golf Club using the PickUp method; the golf club is
then stored in the Golfer’s club field. The Golfer’s holding property is true when its golf club
field is not null. When the Golfer is told to Swing, the following occurs:
If the Golfer is holding a golf club:
“Breathe and focus” is printed to the console. (b) The Golfer tells its club to swing.
Else…
“Where is my caddy?” is printed to the console.
GolfClub: Any golf club that can be swung; a GolfClub can also be held by a Golfer. GolfClub
is an abstract base class.
Putter: A Putter is a GolfClub that, when swung, prints “putt putt putt”.
SandWedge: A SandWedge is a GolfClub that can be swung 5 times before it is thrown in
frustration. (The constructor sets the swing counter to 5 and calling the Throw method resets
the play counter to 5.) When a SandWedge is swung, it does one of two things: if the remaining swing count is larger than zero, it prints “I am in my happy place” and the swing count is
decremented by one; otherwise it prints “hand me my hockey stick”.
My problem:
Code that uses a Golfer object may, therefore, ask for a specific golf club to be operated by referring
to that GolfClub by name. I'm not expected to get input from the user, just embedding it directly in Program.cs is totally fine. So basically a golfer wants to play, either select putter or sandwedge.
My code:
Program.cs
namespace Test
{
public class Program
{
private enum GolfKind
{
Putter, SandWedge
}
public static void Main(string[] args)
{
Golfer golfer = new Golfer();
Putter putt = new Putter();
SandWedge sandwedge = new SandWedge();
golfer.PickUp(putt);
golfer.PickUp(sandwedge);
if (golfer.Holding == true)
{
Console.WriteLine("Breate and Focus");
golfer.Swing(putt);
golfer.Swing(sandwedge);
}
else
{
Console.WriteLine("Where is my Caddy?");
}
Console.ReadLine();
}
}
}
GolfClub.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace Test
{
public abstract class GolfClub
{
public GolfClub() { }
public abstract void Swing();
}
}
Golfer.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Test
{
public class Golfer
{
private List<GolfClub> _clubs;
public Golfer()
{
_clubs = new List<GolfClub>();
}
public bool Holding
{
get
{
if(_clubs.Count() != 0)
{
return true;
}
else
{
return false;
}
}
}
public void PickUp(GolfClub club)
{
_clubs.Add(club);
}
public void Swing(GolfClub club)
{
foreach (GolfClub gc in _clubs)
{
if (gc == club)
{
gc.Swing();
}
}
}
}
}
SandWedge.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace Test
{
public class SandWedge : GolfClub
{
private int _count;
public SandWedge()
{
_count = 5;
}
public override void Swing()
{
while(_count > 0)
{
Console.WriteLine("I am in my happy place");
_count--;
}
if (_count == 0)
{
Console.WriteLine("hand me my hockey stick");
}
}
public void Throw()
{
_count = 5;
}
}
}
Putter.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace Test
{
public class Putter : GolfClub
{
public Putter () {}
public override void Swing()
{
Console.WriteLine("putt putt putt");
}
}
}
You can use a IDictionary<string, GolfClub> to associate a name with a golf club. Provide the name as a new argument for the PickUp() method. Then use a string argument in the Swing() method to find the right club.
public class Golfer
{
private readonly IDictionary<string, GolfClub> _clubs = new Dictionary<string, GolfClub>();
// [...]
public void PickUp(GolfClub club, string name) {
_clubs.Add(name, club);
}
public void Swing(string name) {
_clubs[name].Swing();
}
}
class Program
{
public static string playerName;
static void Main(string[] args)
{
playerName = Console.ReadLine();
}
public static void userInterface()
{
Console.Writeline("Name:" + playerName)
}
}
Been trying to understand where im falling short for a few hours now and cannot figure it out, wondering if any of the SO residents can help me.
Im trying to display a inputted username in a GUI using C# console, I have defined it as a public variable in the class and called it in the method, however its throwing me this exception and displaying a null value?
Any help is appreciated.Class and Main The method im trying to call the variable to
EDIT the desired aim is to have the program display the users inputted username in the UI at the top of the console
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Player player = new Player
{
Name = "name coming from your input class"
};
UserInterface userInterface = new UserInterface(player);
}
}
class UserInterface
{
public UserInterface(Player player)
{
Console.SetWindowSize(220, 55);
Console.WriteLine("Name: {0}", player.Name);
}
}
class Player
{
public string Name { get; set; }
}
}
Or something alike. So you need to provide values for your variables.
Just call the method userInterface() after this line playerName = Console.ReadLine();
this will display the accepted value on console.
I'm new to C# - this is nearly my first program. I'm trying to create some public static variables and constants to use anywhere in the program. The - wrong - way I have tried is to declare them in a separate class in the same namespace but they are out of context for the main program. It's a WPF application. The code looks like this:
namespace testXyz
{
class PublicVars
{
public const int BuffOneLength = 10000;
public static int[] Buff1 = new int[BuffOneLength];
public const int BuffTwoLength = 2500;
public static int[] Buff2 = new int[BuffTwoLength];
private void fillBuff1()
{
Buff1[0] = 8;
Buff1[1] = 3;
//etc
}
private void fillBuff2()
{
Buff2[0] = 5;
Buff2[1] = 7;
//etc
}
}
}
Second file:
namespace testXyz
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public static int isInContext = 0;
int jjj = 0, mmm = 0;
private void doSomething()
{
isInContext = 5; // this compiles
if (jjj < BuffOneLength) // "the name 'BuffOneLength' does not exist in the current context"
{
mmm = Buff2[0]; // "the name 'Buff2' does not exist in the current context"
}
}
}
}
My actual program is much longer of course. I created the above WPF application exactly as shown to test this problem and I got these errors, also occurring in the real program. I really don't want to fill the arrays in the main program as they are very long and it would mean much scrolling. I also want to have one place where I can declare certain public static variables. What is the right way to do this?
You have to either specify class:
// BuffOneLength from PublicVars class
if (jjj < PublicVars.BuffOneLength) {
...
// Buff2 from PublicVars class
mmm = PublicVars.Buff2[0];
or put using static:
// When class is not specified, try PublicVars class
using static testXyz.PublicVars;
namespace testXyz {
public partial class MainWindow : Window {
...
// BuffOneLength - class is not specified, PublicVars will be tried
if (jjj < BuffOneLength) {
mmm = Buff2[0];
You can't access a static variable that is in another class by just calling the variable. You need to first go thru the class that contains it in your case it would be
PublicVars.BuffOneLength
and
PublicVars.Buff2[0]
I have two classes: Action class, that has a method for executing VBScript files, and Item class that contains a list of Action instances. My problem is that I want to limit the number of VBScript files that can be run at the same time. I have no experience with this, and I have googled and searched around, but found nothing. My only idea of how to do is is presented here:
using System;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
namespace Test
{
public class Action
{
public string Script;
public static int Limit;
public static int ActiveCount = 0;
public Process process = new Process();
public Action(string script)
{
Script = script;
}
public void Execute()
{
process.EnableRaisingEvents = true;
process.Exited += new EventHandler(Handler);
try
{
if (ActiveCount < Limit)
{
process = Process.Start(
"c:\\windows\\system32\\wscript.exe",
"\"" + Script + "\"");
ActiveCount++;
}
}
catch(Win32Exception e)
{
}
}
private void Handler(
object sender, EventArgs e)
{
ActiveCount--;
}
}
public class Item
{
public ArrayList Actions = new ArrayList();
}
class Program
{
static void Main()
{
Action.Limit = 5;
Item item = new Item();
item.Actions.Add(
new Action("C:\\Scripts\\Test_1.vbs"));
for (int i = 0; i < 10; i++)
{
foreach (Action action in item.Actions)
{
action.Execute();
Console.WriteLine(Action.ActiveCount);
}
}
}
}
}
The requirement of limiting the number of created processes seems common to me, but as I said, I haven't been able to find any samples I could build on. My question is: what is the common or usual way of doing this? (I also haven't been able to find any samples here on StackOverFlow, so if there are any, please post the link). Any hint or a link is welcome.
Well what you've got will work.
I'm not sure what the fact that you can't find more information tells you.
It's either that you're trying to solve a non-problem - but if your scripts are large and complex or need access to shared resources then limiting the number that run would seem to be a good idea; or it's that your solution is the right one and it's so trivial no one else has thought to raise it.