Unexpected Symbol for Project - c#

I'm having some trouble understanding why "unexpected symbol" exists for my code. I'm using for loops for a project and these few lines of code are giving me problems. I'm guessing it has something to do with not putting brackets/ semi-colins somewhere, but I don't know where it would be. Could I get some help identifying where I need to correct this error?
enter image description here
enter image description here
Here's the full code where the errors exist
// Use this for initialization
void Start()
{
string[] imagesNames = new string[3] { "portrait01", "portrait02", "portrait03" };
//images [0] = CreateSprite ("portrait01");
//images[1] = CreateSprite ("portrait02");
//images[2] = CreateSprite ("portrait03");
string[] professionNames = new string[3] {"Karate fighter", "Ninja Figher", "Samurai Fighter"};
string[] professionDescriptions = new string[3] { "Use hand to hand combat for powerful attacks! Req: Strength = 13 and Special = 10",
"Use high stealth and sneak attacks to suprize you enemies! Req: Speed = 15 or Strength = 9",
"Use your wisdom to reverse attacks with 2x the power! Req: Wisdom = 14 or Special = 13" };
string[] professionImageNames = new string[3] { "profession01", "profession02", "profession03"};
int[] [] minRequirements = { new int [3] {11, 11, 12}, new int[3] {11,13,12}, new int[3] {11,11,16} };
professions = new Profession[3]
for (int i = 0; i < 3; i++)
{
professions[i] = CreateProfession (name[i], description[i], profimages[i], minRequirements[i]);
}
for (int i = 0; i < professionNames.Length; i++) //this starts at least one of the loops
{
profession[i] = createItem(professionNames[i], professionDescriptions[i], professionImageNames[i], minRequirements[i]);
}
//profession01 = createItem("Karate Fighter", "Use hand to hand combat for powerful attacks!", "portrait01");
//profession02 = createItem("Ninja Fighter", "Use high stealth and sneak attacks to suprize you enemies!", "portrait02");
//profession03 = createItem("Samurai Fighter", "Use your wisdom to reverse attacks with 2x the power!", "portrait03");
for (int i = 0; i < imagesNames.Length; i++) //creates a for loop for the images
{
images[i] = CreateSprite(imagesNames[i]); //makes it so the images come from CreatSprite
//array
}
portraitImage.sprite = images[currentImage]; //renders the current images
profession.characterManager = this;
for (in i = 0; i < minRequirement.Length; i++) {
profession.requirements [i] = profession.CreateRequirement { Attribute [i], minRequirement[i];
}
return profession;
}

You are missing a ; on this line:
professions = new Profession[3]
These types of errors should be pretty apparent, usually you always want to inspect the line above the first error, missing a semi-colon is probably the most common programming "error", and it was a lot worse before IDE's highlighted error lines.
The second error, as pointed out by Lazy Coder, is a missing t on the last for loop:
for (int i = 0; i < minRequirement.Length; i++)
Again, should be apparent from reviewing the errors. It should be giving an error "Identifier expected; 'in' is a keyword"

// Use this for initialization
void Start()
{
string[] imagesNames = new string[3] { "portrait01", "portrait02", "portrait03" };
//images [0] = CreateSprite ("portrait01");
//images[1] = CreateSprite ("portrait02");
//images[2] = CreateSprite ("portrait03");
string[] professionNames = new string[3] {"Karate fighter", "Ninja Figher", "Samurai Fighter"};
string[] professionDescriptions = new string[3] { "Use hand to hand combat for powerful attacks! Req: Strength = 13 and Special = 10",
"Use high stealth and sneak attacks to suprize you enemies! Req: Speed = 15 or Strength = 9",
"Use your wisdom to reverse attacks with 2x the power! Req: Wisdom = 14 or Special = 13" };
string[] professionImageNames = new string[3] { "profession01", "profession02", "profession03"};
int[] [] minRequirements = { new int [3] {11, 11, 12}, new int[3] {11,13,12}, new int[3] {11,11,16} };
professions = new Profession[3] //WERE IS THE PROFESSION CLASS CREATED?
//PROFESSIONS NEEDS TO HAVE A TYPE var profession = new Proffession[3];
for (int i = 0; i < 3; i++)
{
professions[i] = CreateProfession (name[i], description[i], profimages[i], minRequirements[i]); //CreateProffession is not implemented on your example, the signature could be like public Profession CreateProfession(string name, string description des, string proofImage, int[] minRequirement)
}
for (int i = 0; i < professionNames.Length; i++) //this starts at least one of the loops
{
//DID YOU MEAN professions
profession[i] = createItem(professionNames[i], professionDescriptions[i], professionImageNames[i], minRequirements[i]);
}
//profession01 = createItem("Karate Fighter", "Use hand to hand combat for powerful attacks!", "portrait01");
//profession02 = createItem("Ninja Fighter", "Use high stealth and sneak attacks to suprize you enemies!", "portrait02");
//profession03 = createItem("Samurai Fighter", "Use your wisdom to reverse attacks with 2x the power!", "portrait03");
for (int i = 0; i < imagesNames.Length; i++) //creates a for loop for the images
{
//DID YOU MEAN imagesNames
images[i] = CreateSprite(imagesNames[i]); //makes it so the images come from CreatSprite
//array
}
portraitImage.sprite = images[currentImage]; //renders the current images //WHERE IS currentImage created?
profession.characterManager = this;
//FOR is for(int i=0 , int with t
for (in i = 0; i < minRequirement.Length; i++) {
profession.requirements [i] = profession.CreateRequirement { Attribute [i], minRequirement[i];
}
return profession;
}

Related

I want to create an array of scene indexes and use it, when i need. The problem is that i don't know how to create the array itself

I did this
public int[] sceneIndex;
public Text[] texts;
IEnumerator ChoosingModes()
{
string[] modes = new string[] { "Cocks", "Tanks", "Cars" };
sceneIndex = new int[] { };
for (int i = 0; i < 5; i++)
{
int x = Random.Range(0, modes.Length);
texts[i].text = modes[x];
sceneIndex[i] = x + 3;
yield return new WaitForSeconds(0.75f);
}
}
It obviously doesn't work, what to do with my in array named 'sceneIndex'?
When you do sceneIndex = new int[] { };, you're locking the length of the length of sceneIndex to 0. Instead, try either sceneIndex = new int[number or scenes]; (locking the length of sceneIndex to the number of scenes you have) or just doing nothing. Since the array is public, you can set the values in the inspector and you won't have to define it in the code.

C# assigning value to array

I'm trying to write a program that would shuffle 13 playing cards from ace to king. Deal 2 cards out and add up the value that's assigned to each card. ace = 11, king = 10, jack = 10, queen = 10, ten = 10, nine = 9, eight = 8 and so on... sort of like blackjack.
so far I'm only able to shuffle the cards and print out two cards randomly but i don't know how to assign a value to each card, add them up and print it out. example, if my two random cards is King and Eight then i would want the program to print out..
King
Eight
18
here's what i got...
static void Main(string[] args)
{
string[] Cards = new string[] {"Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "jack", "Queen", "King", "Ace"};
for (int x = 0; x < 100; x++) // looping the shuffle 100 times to maximize the randomness
{
for (int i = Cards.Length; i > 0; i--) //shuffle
{
string temp;
Random random = new Random();
int r = random.Next(i);
temp = Cards[r];
Cards[r] = Cards[i-1];
Cards[i-1] = temp;
}
}
Console.WriteLine(Cards[0]); //first random card
Console.WriteLine(Cards[1]); //second random card
Console.ReadKey();
}
For a great example of programming a card game, do a google search for KarliCards from the book Beginning Visual C# 2012 (you can easily find a full PDF, but I won't post a link because I'm not sure if it's legal). It has lots of stuff like how to use regular operators (+) on things like classes or structs.
Anyway, what you're looking for is an enum. It's very similar to the Dictionary(string)(int) suggested by Rob (I'm not sure how to write triangle brackets). Here's an example of how it works:
enum CardValue
{
One = 1,
Two = 2,
Three = 3,
Four = 4
}
static void Main(string[] args)
{
int myInt = (int)CardValue.One;
Console.WriteLine("output should be 1: " + myInt);
int mySum = (int)CardValue.One + (int)CardValue.Three;
Console.WriteLine("output should be 4: " + mySum);
Console.ReadKey();
}
My first language was Perl, so I tend to see everything as a struct instead of a class. There's always more than one way to do it....
public enum CardSuits
{
Clubs,
Spades,
Hearts,
Diamonds
}
public enum CardValues
{
Ace = 1,
Two = 2,
Three = 3,
Four = 4
}
public struct Card
{
public CardValues Value; // Card.Value = CardValues.Ace
public CardSuits Suit; // Card.Suit = CardSuits.Spades
public override string ToString()
{
// Card.ToString() == "Ace of Spades"
return String.Format(Value + " of " + Suit);
}
public string ToStringAsInteger()
{
// Card.ToStringAsInteger() == "1 of Spades"
return String.Format((int)Value + " of " + Suit);
}
}
static void Main(string[] args)
{
Card AceOfSpades = new Card();
AceOfSpades.Value = CardValues.Ace;
AceOfSpades.Suit = CardSuits.Spades;
Card TwoOfClubs = new Card();
TwoOfClubs.Value = CardValues.Two;
TwoOfClubs.Suit = CardSuits.Clubs;
int mySum = (int)AceOfSpades.Value + (int)TwoOfClubs.Value;
Console.WriteLine("Sum of Ace (1) and Two (2) is: " + mySum); // should be 3
Console.WriteLine("output of AceOfSpades.ToString() is: " + AceOfSpades.ToString());
Console.WriteLine("output of AceOfSpades.ToStringAsInteger is: " + AceOfSpades.ToStringAsInteger());
Console.ReadKey();
}
Here's how I would do this:
var cards = new Dictionary<string, int>()
{
{ "Two", 2 }, { "Three", 3 }, { "Four", 4 }, { "Five", 5 }, { "Six", 6 },
{ "Seven", 7 }, { "Eight", 8 }, { "Nine", 9 }, { "Ten", 10 }, { "Jack", 10 },
{ "Queen", 10 }, { "King", 10 }, { "Ace", 11 },
};
var random = new Random();
var selected = cards.OrderBy(c => random.Next()).Take(2).ToArray();
foreach (var card in selected)
{
Console.WriteLine(card.Key);
}
Console.WriteLine(selected.Sum(c => c.Value));
Running this, I get (for example):
Two
Ten
12
Now, just for a bit more info on your existing code.
Calling Random random = new Random(); within a loop will result in many (if not all) of the random numbers being the same. You should use a single instance of Random only.
There is no need for the for (int x = 0; x < 100; x++) loop as a single pass of the for (int i = Cards.Length; i > 0; i--) loop is sufficient to randomize the cards.

name is not incrementing by 1 after number 45

i am trying to add a location name to my output text files.
As you can see my numbers are incrementing properly. But i have coded like after number 45 i need to reset the number to 1, also the Carousel:45 should change to ** Carousel1:1**. But it is not happening... why it is not happening. any help please!!!!
My code snippet:
public void just_create_text()
{
//Here we are exporting header
string[] strLines = System.IO.File.ReadAllLines(textBox1.Text);
string CarouselName = enter.Text;
int[] cols = new int[] { 15, 15, 25, 15, 15 };
StringBuilder sb = new StringBuilder();
string line = RemoveWhiteSpace(strLines[0]).Trim();
string[] cells = line.Replace("\"", "").Split('\t');
for (int c = 0; c < cells.Length; c++)
sb.Append(cells[c].Replace(" ", "_").PadRight(cols[c]));
sb.AppendLine("Location".PadRight(15));
sb.AppendLine();
int tmpCarousel = 0;
int carouselNumber = 0;
Dictionary<string, int> namesForCarousels = new Dictionary<string, int>();
for (int i = 0; i < textfile.Count; i++)
{
for (int c = 0; c < cells.Length; c++)
sb.Append(textfile[i].Cells[c].Replace(" ", "_").PadRight(cols[c]));
string name = textfile[i].Cells[1];
if (namesForCarousels.TryGetValue(name, out tmpCarousel) == false)
{
carouselNumber++;
if (carouselNumber > 45)
carouselNumber = 1;//resetting to number1, but name is
//not changing to Carousel1..
namesForCarousels[name] = carouselNumber;
}
var strCorousel = lstMX.Find(x => x.MAX_PN.Equals(name)).Carousel;
strCorousel = (String.IsNullOrEmpty(strCorousel)) ? CarouselName : strCorousel;
sb.Append(String.Format("{0}:{1}", strCorousel, carouselNumber).PadRight(15));
sb.Append("\r\n");
}
System.IO.File.WriteAllText(#"Z:\Desktop\output.TXT", sb.ToString());
}
OUTPUT i need
I need after Carousel:45 >>> i need Carousel1:1. How can i do this..?
You never use the numbers stored in your dictionary namesForCarousels after setting them. Probably you want
sb.Append(String.Format("{0}:{1}", strCorousel, namesForCarousels[name]).PadRight(15));
Also, you should rename carouselNumber to something like carouselNumberCounter. It's not the number of the current carousel, it's a counter used to assign a number to the next carousel. And for additional clarity, get rid of the local variable tmpCarousel and do:
if (!namesForCarousels.ContainsKey(name))
{
You might find it easier to follow your code if you use more descriptive variable names. It's not entirely clear what you're trying to do, but I assume you want to re-use the same carousel number for a given "Max Pn" if you've already allocated it - at the moment, you populate that mapping but you don't use it, you are reliant on max pn being in order. I don't actually see why carousel number wouldn't reset, but if you tidy it up perhaps you have a better chance of seeing what is happening.
Also given your null reference exception from your other question, this protects against that - though it probably indicates another problem elsewhere in the population of your "lstMx".
public static void just_create_text()
{
//Here we are exporting header
string[] strLines = System.IO.File.ReadAllLines(textBox1.Text);
string defaultCarouselName = enter.Text;
int[] columnPaddings = new int[] { 15, 15, 25, 15, 15 };
StringBuilder completedOutputBuilder = new StringBuilder();
string line = RemoveWhiteSpace(strLines[0]).Trim();
string[] cells = line.Replace("\"", "").Split('\t');
for (int c = 0; c < cells.Length; c++)
completedOutputBuilder.Append(cells[c].Replace(" ", "_").PadRight(columnPaddings[c]));
completedOutputBuilder.AppendLine("Location".PadRight(15));
completedOutputBuilder.AppendLine();
int carouselNumberForEntry = 0;
Dictionary<string, int> maxPnToCarouselNumber = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
for (int i = 0; i < textfile.Count; i++)
{
for (int c = 0; c < cells.Length; c++)
completedOutputBuilder.Append(_textfile[i].Cells[c].Replace(" ", "_").PadRight(columnPaddings[c]));
string maxPnForEntry = textfile[i].Cells[1];
int previouslyAllocatedCarouselNumberForMaxPn = 0;
if (maxPnToCarouselNumber.TryGetValue(maxPnForEntry, out previouslyAllocatedCarouselNumberForMaxPn) == false)
{
// assign a new courousel number for this max pn
carouselNumberForEntry++;
if (carouselNumberForEntry > 45)
carouselNumberForEntry = 1;
// for better clarity use add
maxPnToCarouselNumber.Add(maxPnForEntry, carouselNumberForEntry);
}
else
{
// use the carousel number previous assigned for this maxPn
carouselNumberForEntry = previouslyAllocatedCarouselNumberForMaxPn;
}
// find the related max pn carousel entry (if relatedPn is not found this suggests a problem elsewhere)
MAX_PN_Carousel relatedPn = lstMx.Find(x => x.MAX_PN != null && x.MAX_PN.Equals(maxPnForEntry, StringComparison.OrdinalIgnoreCase));
// assign the name from the entry, or use the default carousel name if unavailable
string carouselNameForMaxPn = (relatedPn == null || String.IsNullOrWhiteSpace(relatedPn.Carousel)) ? defaultCarouselName : relatedPn.Carousel;
// add the new column in the output
completedOutputBuilder.Append(String.Format("{0}:{1}", carouselNameForMaxPn, carouselNumberForEntry).PadRight(15));
completedOutputBuilder.Append("\r\n");
}
System.IO.File.WriteAllText(#"c:\dev\output.TXT", completedOutputBuilder.ToString());
}

Unity 4 C# - IndexOutOfRangeException: Array index is out of range

Apologies if this is answered somewhere else but I believe my problem is very specific and I haven't got the slightest clue, based on past experience in python, why this code returns the error:
IndexOutOfRangeException: Array index is out of range.
(wrapper stelemref) object:stelemref (object,intptr,object)
MissionGen.Start () (at Assets/Scripts/MissionGen.cs:59)
I am currently in the process of learning C# in the Unity engine, and have created a small class experimentation script designed to generate missions using OOP, selecting target names from an array - but obviously, I have no idea why this won't work. As I believe the equivalent error in python only occurs when I have tried to refrence an array element that doesn't exist. And though this is probably also the case here, due to the way the code is written, I don't understand why. Anyway, here is the full script!:
// Simple mission generation script, using arrays and object orientated programming. Designed to be
// upgraded at a later date.
using UnityEngine;
using System.Collections;
// Mission generation template
public class MissionGen : MonoBehaviour {
public string[] t_list_t = new string[] {"Dave", "Johnson", "Hadaki", "Tim", "Timothy", "Chris Roberts"};
public string[] t_list_c_col = new string[] {"Blue", "Yellow", "Green", "Black", "Orange", "Purple"};
public string[] t_list_h_col = new string[] {"Black", "Green", "Orange", "Blue", "Red", "Brown"};
public class MissionTemplate {
// Mission properties
public int id;
public string t_name;
public string t_coat;
public string t_hat;
public string type;
public int reward1;
public string reward2;
// A method, for displaying the attributes of an individual mission.
public void ShowMission () {
print ("MISSION ID: " + id);
print ("TARGET NAME: " + t_name);
print ("TARGET COAT COLOUR: " + t_coat);
print ("TARGET HAT COLOUR: " + t_hat);
print ("MISSION TYPE: " + type);
print ("REWARD 1 (Money): " + reward1);
print ("REWARD 2 (Item): " + reward2);
}
}
// Mission array generation. Change the array range to generate more missions for use in the game.
void Start() {
// Change this variable to decide how many missions to generate:
int gen = 50;
// Change the above variable to designate the number of missions to generate.
MissionTemplate[] MISSION = new MissionTemplate[gen];
for (int i = 1; i <= gen; i++)
{
int t_pick = Random.Range (0,5);
int t_coat_col = Random.Range (0,5);
int t_hat_col = Random.Range (0,5);
MISSION[i] = new MissionTemplate();
MISSION[i].id = i;
MISSION[i].t_name = t_list_t[t_pick];
MISSION[i].t_coat = t_list_c_col[t_coat_col];
MISSION[i].t_hat = t_list_h_col[t_hat_col];
MISSION[i].type = "Assassination";
MISSION[i].reward1 = 0;
MISSION[i].reward2 = "";
}
for (int i = 1; i <= gen; i++)
{
MISSION[i].ShowMission();
}
}
}
As a breakdown, I believe the problems arise between the following code:
for (int i = 1; i <= gen; i++)
{
int t_pick = Random.Range (0,5);
int t_coat_col = Random.Range (0,5);
int t_hat_col = Random.Range (0,5);
MISSION[i] = new MissionTemplate();
MISSION[i].id = i;
MISSION[i].t_name = t_list_t[t_pick];
MISSION[i].t_coat = t_list_c_col[t_coat_col];
MISSION[i].t_hat = t_list_h_col[t_hat_col];
MISSION[i].type = "Assassination";
MISSION[i].reward1 = 0;
MISSION[i].reward2 = "";
}
for (int i = 1; i <= gen; i++)
{
MISSION[i].ShowMission();
}
}
}
And:
public class MissionGen : MonoBehaviour {
public string[] t_list_t = new string[] {"Dave", "Johnson", "Hadaki", "Tim", "Timothy", "Chris Roberts"};
public string[] t_list_c_col = new string[] {"Blue", "Yellow", "Green", "Black", "Orange", "Purple"};
public string[] t_list_h_col = new string[] {"Black", "Green", "Orange", "Blue", "Red", "Brown"};
Any help would be much appreciated!
Thanks,
This is the problem:
MissionTemplate[] MISSION = new MissionTemplate[gen];
for (int i = 1; i <= gen; i++)
{
...
MISSION[i] = new MissionTemplate();
Aside from violating normal naming conventions, arrays in C# are 0-based - for example, the valid indexes for an array of length 5 are 0, 1, 2, 3 and 4.
So your for loop should be:
for (int i = 0; i < gen; i++)
Or more "obviously correctly" (IMO):
for (int i = 0; i < MISSION.Length; i++)
That makes it obvious to anyone reading the code that you're staying within the bounds of the MISSION array, without having read the array creation statement.

Array of string not working

I use a simple array: contentHouseOne[] that contains strings. But in the Do/While loop it isn't working! It seems like the code don't understand that it's a string when a new object is to be created!? It works when I hardcode the string like I show below. Help is preciated! Thanks!
This isn't working:
listHouseParts.Add(new HousePart(content, contentHouseOne[i], newPosition));
But this works:
listHouseParts.Add(new HousePart(content, "100x100", newPosition));
EDIT:
Here are some code to declare arrays
string[] contentHouseOne = new string[] { "ruta100x100Red",
"ruta100x100Grey",
"ruta100x100Green",
"ruta100x100Yellow",
"ruta100x100Blue" };
bool[,] occupiedPositions = new bool[500,500];
Here are some code to set all grid positions to false
for (int i = 0; i < gridCol; i++)
for (int ii = 0; ii < gridRow; ii++)
occupiedPositions[i, ii] = false;
And finally here are the code that I have the problem
int i = 0;
do
{
Vector2 newPosition = NewRandomPosition;
if (occupiedPositions[(int)newPosition.X, (int)newPosition.Y] == false)
{
listHouseParts.Add(new HousePart(content,
contentHouseOne[i], newPosition));
occupiedPositions[(int)newPosition.X, (int)newPosition.Y] = true;
i++;
}
}
while (i <= 5);
Your string array includes five elements:
string[] contentHouseOne = new string[] { "ruta100x100Red",
"ruta100x100Grey",
"ruta100x100Green",
"ruta100x100Yellow",
"ruta100x100Blue" };
But your while loop ends if your running variable i is greater than 5
while (i <= 5);
which causes a IndexOutOfBounds exception on contentHouseOne, because the 6th element at index 5 isn't defined.
You should change your while condition to (i < 5).
Try this so atleast you know if its empty or not
HousePart housePart = new HousePart();
housePart.Content = content;
if (!string.IsNullOrEmpty(contentHouseOne[i]))
housePart.ContentHouseOne = contentHouseOne[i];
else
housePart.ContentHouseOne = string.Empty;
housePart.NewPosition = newPosition;
listHouseParts.Add(housePart);

Categories

Resources