Its the first time I've used this forum! I'm a second year university student and have just started writing code in C# (as were we did java last year).
One of the lab exercises is to write a small program that pops up a terminal window asks for a number (decimal number) this is meant to be the radius the program calculates the area by calling the method from another class!
I've written the code in Visual Studio 2008, using the same namespace, it builds and runs but doesn't work?
Here is the code with the different classes, any help/advice would be appreciated.
The Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Program4
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter The Radius:");//Text to be displayed in the console
Console.ReadLine();//Read the line and store information in temp directory
Pie one = new Pie();//Calls the method from the class in the same namespace
Console.ReadKey();//Reads and displays the next key pressed in the console
Environment.Exit(0);//Exit the Enviromet
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Program4
{
class Pie
{
public void Pin ()
{
int r;//defining the value that is going to be entered as an integer
double result;//declaring the result string as a double
r = (int)Convert.ToDouble(Console.ReadLine());
result=(3.14*r*r);//the calculation to work out pie
Console.WriteLine("The Radius of the circle is " + (result));//the writeline statement
}
}
}
You could try running the code:
Pie one = new Pie();
one.Pin();
Also:
this line:
Console.ReadLine();//Read the line and store information in temp directory
that comment is very wrong. It should be //Read the line and throws the result away
and this: (int)Convert.ToDouble(Console.ReadLine());
could be replaced by this: int.Parse(Console.ReadLine())
add static to class Pie and public void Pin(). It will work
static class Pie
{
public static void Pin ()
{
int r;//defining the value that is going to be entered as an integer
double result;//declaring the result string as a double
r = (int)Convert.ToDouble(Console.ReadLine());
result=(3.14*r*r);//the calculation to work out pie
Console.WriteLine("The Radius of the circle is " + (result));//the writeline statement
}
}
or if you prefer you can instantiate the class and then call the method like that
Pie pie=new Pie();
pie.Pin();
Related
This is my original code and it's working fine but the text content is already in the editor in a Text UI and therefore it's also in the variable textField.
So I don't want to type the text over again also inside the code. For example the word toBeSearched is "almost" so using the string format it will generate new random number each time I press on space between the words: "almost" and "hours".
But since the text is already in the textField variable I want to parse the place I want to add the random numbers automatic using indexof and substring.
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using UnityEngine.UI;
public class CustomText : MonoBehaviour
{
public string toBeSearched;
public Text textField;
private void Start()
{
GenerateRandomHour();
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
GenerateRandomHour();
}
}
private void GenerateRandomHour()
{
string numberName = Random.Range(1, 10).ToString();
textField.text = string.Format("Hello my friend, It's about time to wakeup. You were sleeping for almost {0} hours. My name is NAVI and i'm your navigation helper in the game.", numberName);
}
}
This is the code with the indexof and substring I tried to use but it#s not working good.
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using UnityEngine.UI;
public class CustomText : MonoBehaviour
{
public string toBeSearched;
public Text textField;
private void Start()
{
GenerateRandomHour();
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
GenerateRandomHour();
}
}
private void GenerateRandomHour()
{
string result = null;
string result1 = null;
int ix = textField.text.IndexOf(toBeSearched);
if (ix != -1)
{
result = textField.text.Substring(0, ix + toBeSearched.Length);
result1 = textField.text.Substring(ix + toBeSearched.Length, textField.text.Length - (ix + toBeSearched.Length));
}
result1 = result1.TrimStart();
string numberName = Random.Range(1, 10).ToString();
textField.text = string.Format(result + " {0} " + result1, numberName);
}
}
Again the word toBeSearched is "almost" and I used a breakpoint and result contain the text until almost: "Hello my friend, It's about time to wakeup. You were sleeping for almost" and the variable result1 contain the rest of the text: "hours. My name is NAVI and i'm your navigation helper in the game."
But now when I'm pressing the space key it's inserting each time a new random number but it's not replacing the whole text like in the original code above.
So the result is many numbers in the text.
Not sure why it's not working like the original code.
The reason why it's not working is because you're changing the value of textField.text, so when you repeat the process the substrings are generated with this new value, including the number. You shouldn't give up your first solution, it's much cleaner. Store the original value of the text field on Start:
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using UnityEngine.UI;
public class CustomText : MonoBehaviour
{
public string toBeSearched;
public Text textField;
private string defaultValue;
private void Start()
{
defaultValue = textField.text;
GenerateRandomHour();
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
GenerateRandomHour();
}
}
private void GenerateRandomHour()
{
string numberName = Random.Range(1, 10).ToString();
textField.text = string.Format(defaultValue, numberName);
}
}
Add the {0} directly to your text field value in the inspector:
Hello my friend, It's about time to wakeup. You were sleeping for almost {0} hours. My name is NAVI and i'm your navigation helper in the game.
The problem is when you are adding a number in a specified spot, so every time you press space, it is using the existing text as the template and thus the old number stays,along with adding a new one.
Instead, you want to search between the two words "almost" and "hours" so you can replace whatevers between them. You can do this the by adding another indexOf search, but itll be easier using regex.
string result = Regex.Replace(textField.text, "(? <=almost).+?(?=hours)" , numberName);
textField.text = result;
Although your first solution looks cleaner, and if you want to keep the text in the inspector, Nathalia's answer would work
I am new at programming and I am trying to create a loop where the while condition is based on variables however I don't know the correct syntax for it.
That's what I am trying to do, even though it may not be allowed...I think.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp3
{
class Program
{
static void Main(string[] args)
{
float totalArea, areaUnbuilt;
while (!float.TryParse(Console.ReadLine(), out totalArea, out areaUnbuilt))
{
Console.Clear();
Console.WriteLine("Insert total area in square meters:");
float.TryParse(Console.ReadLine(), out totalArea);
Console.WriteLine("Insira are not built in square meters:");
float.TryParse(Console.ReadLine(), out areaUnbuilt);
}
}
}
}
You can't use TryParse to get back two out values. Instead change your code to a do..while loop
bool isArea = true;
bool isUnbuilt = true;
do
{
Console.Clear();
Console.WriteLine("Insert total area in square meters:");
isArea = float.TryParse(Console.ReadLine(), out totalArea);
Console.WriteLine("Insert area not built in square meters:");
isUnbuilt = float.TryParse(Console.ReadLine(), out areaUnbuilt);
} while( !isArea || !isUnbuilt);
I am an LSPDFR developer and I am building a callout. I am trying to get my spawn point to spawn at a certain coordinate.
I currently have:
SpawnPoint = World.GetNextPositionOnStreet(new Vector3(-2051.99463, 3237.05835, 1456.97021));
This is in C#. I get the error Argument 1: cannot convert from 'double' to 'float'. Does anyone know what to do? And I am also writing this in Visual Studio
I have tried removing:
private Vector3 SpawnPoint;
You need to add 'J' to the end of each coordinate.
This is a very old topic, but there are no answer ..
I searched for LSPDFR -An addon for GTAV. I had hoped for a lot of activity
There was not..
Anywitch
Someone may browse for this so i will add the way to do this in LSPDFR
Firstly To get a point inside the game-world:
Press F4
In console write:
PrintInfo
Press Enter
Now you have 3 values that represent a 3Dvector
Z is UP!
Lets say we got
x:111, y:222 z:10
Script:
In your variables define a spawnpoint
public Vector3 SpawnPoint;
You can now say
SpawnPoint = new Vector3(111.0f, 222.0f, 10.0f);
and use that as a position for a object.
You can also use an object, Ped, or your player, and set a spawnpoint close by:
SpawnPoint = World.GetNextPositionOnStreet(
Game.LocalPlayer.Character.Position.Around(300f));
That will make a spawn around 300 world meters from current pos your player is in.
So that is two different ways to make a spawn-position in LSPDFR.
CODE
//will spawn a car 10 tiks from player if key J is pressed
using LSPD_First_Response;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Rage;
using Rage.Native;
using LSPD_First_Response.Mod.API;
using LSPD_First_Response.Mod.Callouts;
using LSPD_First_Response.Engine.Scripting.Entities;
using Rage.Attributes;
[assembly: Plugin("spawn car", Description = "spawns a car", Author = "mb")]
namespace Example
{
public static class SpawnCar
{
private static void Main()
{
public Vector3 SpawnPoint;
while (true)
{
if (Game.IsKeyDown(System.Windows.Forms.Keys.J))
{
SpawnPoint = World.GetNextPositionOnStreet(
Game.LocalPlayer.Character.Position.Around(10.0f));
aaVehicle = new Vehicle("BALLER", SpawnPoint);//100 of cars are available
}
GameFiber.Yield();
}
}
}
}
I have an array InputFields, in my situation - six InputFields. How can I get the text and save it from each InputField?
Everything should work like this: I turn on the app, I change one, two or all of the input field, then turn off the application. Again, I turn on, and input fields have to be values which I wrote earlier.
I have a code that must seem to work properly, but this code works like this: it takes only the last value entered by the user and writes it to the last input field.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class SaveText : MonoBehaviour {
public GameObject[] InputFields;
public static string n;
public void Start ()
{
for(int i = 0; i < InputFields.Length; i++)
{
InputFields[i].GetComponent<InputField> ().text = PlayerPrefs.GetString (InputFields[i].name);
Debug.Log (PlayerPrefs.GetString (InputFields[i].name));
n = InputFields[i].name;
var input = InputFields[i].GetComponent<InputField> ();
var se = new InputField.SubmitEvent ();
se.AddListener (SubmitName);
input.onEndEdit = se;
}
}
public void SubmitName(string arg)
{
PlayerPrefs.SetString (n, arg);
}
An array of input fields I initialize dragging in Unity each input field in free cell in Script Component.
Well, you are using a single variable for all the different player prefs variables, n. So when you change a field (with SubmitName) it uses that n pref variable and changes it. This will correspond to the last value you gave to n in your loop.
An option would be to have that be an array too (private string prefValues[]) or to pass the calling input field to SubmitName (or rather it's name) and use that instead of n.
A little example (from your code you can actually change your GameObject[] to InputField[] which saves some GetComponent calls):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class EventTest : MonoBehaviour
{
public InputField[] inputFields;
void Start ()
{
foreach(InputField field in inputFields)
{
var se = new InputField.SubmitEvent();
se.AddListener(delegate {
SubmitText(field.name, field.text);
});
field.onEndEdit = se;
}
}
public void SubmitText(string prefKey, string prefVal)
{
Debug.Log("Saved " + prefVal + " to " + prefKey);
}
}
Edit:
Added lines for saving/loading from prefs in the code below. For my test setup I just have two scenes. Both have two input fields and a button that calls that scene change. I can type stuff on the fields as I like, change scenes and it stays. Also upon restarting playmode in the editor.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class EventTest : MonoBehaviour
{
public InputField[] inputFields;
void Start ()
{
foreach(InputField field in inputFields)
{
// Get field values from player prefs if existing
// (it should only not exist the very first time or if you delete/clear the prefs)
if(PlayerPrefs.HasKey(field.name))
field.text = PlayerPrefs.GetString(field.name);
var se = new InputField.SubmitEvent();
se.AddListener(delegate {
SubmitText(field.name, field.text);
});
field.onEndEdit = se;
}
}
public void SubmitText(string prefKey, string prefValue)
{
// store the typed text of the respective input field
PlayerPrefs.SetString(prefKey, prefValue);
}
public void ChangeScene()
{
if(SceneManager.GetActiveScene().name == "Scene1")
{
SceneManager.LoadScene("Scene2");
}
else
{
SceneManager.LoadScene("Scene1");
}
}
}
If you want to save the data, after the application stopped or if it gets paused, you need to add some more functions to your MonoBehavior so that it can handle additional actions on a system end or pause.
Look at following functions in the documentation
OnApplicationQuit()
OnApplicationPause()
These functions will be called automatically. Inside these functions you need to iterate through the textfields and save them. It is one of the last functions that will be called before the program will lose it's recourses.
Regarding the Scene change, you would need the new scene to tell the old one to do any further actions. Like you can read in this post, there is only a way to know if a new scene was loaded.
Maybe you have a place where you can save the last active scene object and then call the last scenes function to do the saving process while the object is not cleared.
I apologize as I don't really know how to describe my problem.
I'm working on a game which contains hundreds of levels, and will consequently contain hundreds of different NPCs. Since this is an MMO-style game where the states of all NPCs will need to be preserved, I've settled on creating a class that keeps track of each instance of every NPC for me, and when a player enters a level, it can provide the list for all of the NPCs in that area, where they go, etc. The problem is that since this NPC Control class stores a multitude of different classes, C# won't allow me to grab the information I need from them such as their x/y/image in my Draw method of my Game1 class since it doesn't know that those variables exist.
My current NPC control class looks like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyWorld
{
public class NpcsControl
{
public List<object> GetNPCs(string levelname)
{
List<object> NPCs = new List<object>();
switch (levelname)
{
case "garden2":
NPC_TreeBreakable NPCtree = new NPC_TreeBreakable();
NPCtree.x = 16;
NPCtree.y = 16;
NPCs.Add(NPCtree);
NPCtree = new NPC_TreeBreakable();
NPCtree.x = 16;
NPCtree.y = 512;
NPCs.Add(NPCtree);
NPC_TestLamp NPCtestlamp = new NPC_TestLamp();
NPCtestlamp.x = 16;
NPCtestlamp.y = 1024;
NPCs.Add(NPCtestlamp);
break;
}
return NPCs;
}
}
}
While my tree NPC code looks like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyWorld
{
public class NPC_TreeBreakable
{
public string image = "tree_new";
public int x;
public int y;
}
}
I need to fetch this in my Game1.cs so that I can show the game where to draw these. Currently it is using this code:
foreach (object o in npcControl.GetNPCs(players[0].level))
{
object ob = o.GetType(); //ob == MyWorld.NPC_TreeBreakable
imgpos.X = ((NPC_TreeBreakable)(o)).x;
imgpos.Y = ((NPC_TreeBreakable)(o)).y;
SpriteTexture = Content.Load<Texture2D>(((NPC_TreeBreakable)(o)).image);
spriteBatch.Draw(SpriteTexture, imgpos, new Rectangle(0, 0, SpriteTexture.Width, SpriteTexture.Height), Color.White);
}
The problem is that I'm being forced to manually input "((NPC_TreeBreakable)(o)).x" or "((NPC_TestLamp)(o)).x" instead of being able to just use ((ob)(o)).x since C# knows that not every class may have an "x", "y", or "image" variable. Even though they will be in each of the NPCs.
How do I fix this so that I can reference variables when C# doesn't know to expect them like this?
Thank you!