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);
Related
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Security.Cryptography.X509Certificates;
using UnityEngine;
using UnityEngine.UI;
public class LetterRandomiser : MonoBehaviour
{
public char[] characters;
public Text textbox;
public InputField mainInputField;
void Start() /*when the game starts*/
{
char c = characters[Random.Range(0,characters.Length)];
textbox.text = c.ToString();
}
void Update()
{
if (Input.GetKeyDown(KeyCode.KeypadEnter) && mainInputField.text.Contains(textbox.text) == true)
{
char c = characters[Random.Range(0, characters.Length)];
textbox.text = c.ToString();
mainInputField.text = "";
}
else if (Input.GetKeyDown(KeyCode.KeypadEnter) && mainInputField.text.Contains(textbox.text) == false)
{
mainInputField.text = "";
}
}
}
Reference to my game
I'm trying to program my game so that the two textboxes (firstChar and secondChar) would choose one randomly generated letter each.
Then when a player types in a word in the input box, the game would check if the word contains the two randomly generated.
If it does, then the program would randomise the two textboxes again and the input field would be blank.
Otherwise the program wouldn't randomise those two textboxes and the player will have to try again.
However the program doesn't work. There are no errors but when I press enter, nothing happens, like shown on the image.
Answered by #DerDingens.
You are checking for KeypadEnter. The normal / big Enter ist Return:
docs.unity3d.com/ScriptReference/KeyCode.KeypadEnter.html.
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 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!
I have a class with this method
rotire.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using System.Collections;
namespace WpfApplication3
{
class rotire:MonoBehaviour
{
float speed = 10f;
public void rotiree()
{
transform.Rotate(new Vector3(15,40,45)*speed,Time.deltaTime);
}
}
}
I want use this method to rotate my cube made in XAML.
Unfortunately it not work and I think my code is incorectly.
Please, can someone help me whit an ideea, what i should write.
Window1,cs
private void Window_Loaded_1(object sender, RoutedEventArgs e)
{
rotire rot = new rotire();
rot.rotiree();
mycube.Transform = rot;
}
I belive the last line of code is wrong, because i receive this error
"Cannot implicitly convert type 'WpfApplication3.rotire' to 'System.Windows.Media.Media3D.Transform3D'"
That last line should be the following:
mycube.Transform = rot.transform;
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();