HOMEWORK QUESTION:
I need to create a simple trivia game that reads from a CSV file. My data for a particular question is structured as follows: "Question;AnswerA;AnswerB;AnswerC;AnswerD;CorrectAnswerLetter".
We're using a series of getters and setters to hold all the relevant data for a single question object, and I'm running into a problem with the array I've created to hold the four answers.
In my constructor, I'm using this code--which I believe instantiates the Answer array in question:
class TriviaQuestionUnit
{
...
const int NUM_ANSWERS = 4;
string[] m_Answers = new String[NUM_ANSWERS];
public string[] Answer
{
get { return m_Answers[]; }
set { m_Answers = value[];
}
...
// Answer array
public string[] GETAnswer(int index)
{
return m_Questions[index].Answer;
}
...
}
I'm accessing the getter and setter from my TriviaQuestionBank method, which includes this code:
...
const int NUM_QUESTIONS = 15;
TriviaQuestionUnit[] m_Questions = new TriviaQuestionUnit[NUM_QUESTIONS];
...
// Answer array
public string[] GETAnswer(int index)
{
return m_Questions[index].Answer;
}
...
I'm using using StreamReader to read a line of input from my file
...
char delim = ';';
String[] inputValues = inputText.Split(delim);
...
parses the input in an array from which I create the question data. For my four answers, index 1 through 4 in the inputValues array, I populate this question's array with four answers.
...
for (int i = 0; i < NUM_ANSWERS; i++)
{
m_Questions[questionCounter].Answer[i] = inputValues[i + 1];
}
...
I'm getting errors of Syntax code, value expected on the getters/setters in my constructor, and if I change the variable to m_Answers[NUM_QUESTIONS] I get an error that I can't implicitly convert string to String[].
Hopefully I've posted enough code for someone to help point me in the right direction. I feel like I'm missing something obvious, but I just cannot make this work.
Your code has some errors that will cause compilation errors, so my first lesson for you is going to be: listen to the compiler. Some of the errors might seem a bit hard to understand sometimes, but I can ensure you that a lot of other people have had the same problems before; googling a compiler error often gives you examples from other people that are similar to your issue.
You say "In my constructor", but the problem is that your code does not have a constructor. You do however initialize fields and properties on your class and surely enough, the compiler will create a default constructor for you, but you have not defined one yourself. I am not saying that your code does not work because you do not have a constructor, but you might be using the wrong terms.
The first problem is in your first code snippet inside TriviaQuestionUnit. Your first two lines are working correctly, you are creating a constant integer with the value 4 that you use to determine how large your array is going to be and then you initialize the array with that given number.
When you do new string[NUM_ANSWERS] this will create an array, with default (empty) values.
The first problem that arises in your code is the getters and setters. The property expects you to return an array of strings which the method signature in fact is telling us:
public string[] Answer
However, looking at the getter and setter, what is it that you return?
m_Answers is a "reference" to your array, hence that whenever you write m_Answers you are referring to that array. So what happens when we add the square brackets?
Adding [] after the variable name of an array indicates that we want to retrieve a value from within the array. This is called the indexer, we supply it with an index of where we want to retrieve the value from within the array (first value starts at index 0). However, you don't supply it with a value? So what is returned?
Listen to the compiler!
Indexer has 1 parameter(s) but is invoked with (0) argument(s)
What does this tell you? It tells you that it doesn't expect the empty [] but it would expect you to supply the indexer with a number, for instance 0 like this: [0]. The problem with doing that here though, is that this would be a miss-match to the method signature.
So what is it that we want?
We simply want to return the array that we created, so just remove [] and return m_Answers directly like this:
public string[] Answer
{
get { return m_Answers; }
set { m_Answers = value; }
}
Note that you were also missing a curly bracket at the end if the set.
When fixing this, there might be more issues in your code, but trust the compiler and try to listen to it!
Related
So I have a very simple bit of code
public static string[] config = File.ReadAllLines(Environment.CurrentDirectory.ToString() + "\\documents\\config.json");
public static void Start()
{
Console.WriteLine(config[4]);
Console.ReadKey();
}
This properly displays the 5th item in the array, which is "0x00=jU0UrZBkqPXfp8MsMoILSRylevQGaUmJRnpFbfUvcGs=7lvpCgtyWl0 : crypt_wallet". I only want the first part of the string, so "0x00=jU0UrZBkqPXfp8MsMoILSRylevQGaUmJRnpFbfUvcGs=7lvpCgtyWl0".
When I use Console.WriteLine(config[4].split(null); or anything else in the split arguments, I just get back System.String[].
How would I fix that so it properly displays the answer?
Should rather be like below since you will have to choose the element to print since Split() returns a string[]
Console.WriteLine(config[4].Split(':')[0]);
Not sure what you mean by the "the first part of the string". But you can achieve this by using .Substring().
If you know that the beginning will always be a fixed length, you can do:
config[4].Substring(0, 4);
If you know the value will be followed by a certain character (like the "=" for an example:
config[4].Substring(0, config[4].IndexOf("="));
I have two script.
Script1
Script2
In Script1 i declared a arraylist it contains value 2, 4, 6, etc...
public static ArrayList aArray= new ArrayList();
function update(){
if(bool1)
{
aArray.Add(i);
}
}
I have to check a value 5 exist in arraylist from Script2.
if value exists i have to get its key.
How to get it?
First, i would recommand using a generic List<T> instead of the non-generic ArrayList, which enables you to specify the type of objects that go into that list (for better type safety).
Also, declaring a variable readonly prevents you from accidently overwriting it, which is often the case with Lists (after all, you can always just Clear them):
public static readonly List<int> items = new List<int>();
Now to answer your actual question, if you want to check if a value exists in the list, you can use the method Contains.
To check if the value does not exist, just put an ! in front of the expression:
if (!Script1.items.Contains(i)) {
// This will only execute if the list does not contain i.
items.Add(i);
}
Try using Contains. This code will detect if you have already the value in the ArrayList and will stop code from adding it a second time.
public static ArrayList aArray= new ArrayList();
function update()
{
if(aArray.Contains(i)==false)
{
aArray.Add(i);
}
}
If you want to remove a value it is just as easy as aArray.Remove(i)
if I understood correctly, Script1 is in your camera, and Script2 is in a Character. For the sake of this example we'll call them MainCamera and Character respectively.
Now, unless I understood wrong, you're trying to access an Array in Script1 from Script2. While the other answers are very much correct, unity3D has a bit of a workaround needed to access it.
Anyway, within Script2 use this:
if(GameObject.Find("MainCamera").GetComponent<Script1>().aArray.Contains(5))
{
//Do your code here
}
I'm trying to consume a DLL-located method in C#, which returns a dynamic array of structs. What ever I do, I receive the well-know "Object reference not set to an instance of an object" error, Here is my last code and it still tells that error:
string v_user = "kish";
string v_pass = "u";
string v_number = "p";
string v_address = "url has been replaced with this string";
string v_cid = "abc";
Cls_SMS.SMSReceive.STC_SMSReceive[] xts;
Cls_SMS.SMSReceive px = new Cls_SMS.SMSReceive();
// *** is the below line
xts = px.ExtendReceiveSMS(v_user, v_pass, v_number, v_address, v_cid);
int upper_bound = xts.GetUpperBound(0);
for (int counter = 0; counter < upper_bound; counter++)
{
Response.Write(xts[counter].Message.ToString());
Response.Write("<br>");
}
please note that my main problem is about receiving a dynamic array of structs with struct type name (Cls_SMS.SMSReceive.STC_SMSReceive) and other aspects such as connecting to the remote server is not my problem. I just want to allocate a dynamic array of vendor-defined structs to the left side of the assignment opeator in * line.
Please help me.
Thank you very much.
It is not clear how the px.ExtendReceiveSMS(v_user, v_pass, v_number, v_address, v_cid); method assigns the array, it probably doesn't assign it at all because of the exception. Here's how you could assign a dynamic array and return it:
public STC_SMSReceive[] ExtendReceiveSMS()
{
STC_SMSReceive[] result = new STC_SMSReceive[2];
result[0] = new STC_SMSReceive();
result[1] = new STC_SMSReceive();
return result;
}
Also if it is dynamic you might also take a look at List<T>:
public IList<STC_SMSReceive> ExtendReceiveSMS()
{
IList<STC_SMSReceive> result = new List<STC_SMSReceive>();
list.Add(new STC_SMSReceive());
list.Add(new STC_SMSReceive());
return result;
}
This has nothing to do with the strict array; simply, the library method you are using is returning null.
There are various possibilities here:
maybe returning null is an expected return value for some scenarios; check the documentation
maybe you need some additional configuration, or maybe you need to call some additional method (GetTheData() would be too hopeful ;p), or wait for some other event before this data is available - check the documentation
maybe it is simply a library bug; contact the vendor
If all 3 routes fail, personally I'd just open it reflector and look for a scenario that might return null. Then tell the vendor to fix the bug or clarify the documentation as appropriate.
If you replace your separate declaration of xts with:
var xts = px.ExtendReceiveSMS(v_user, v_pass, v_number, v_address, v_cid);
what type does Visual Studio now report xts to be?
You can tell by hovering over xts with your cursor and reading it off the tooltip.
Other than that if the vendor is reporting that it works for other users, you must have one (or more) of the arguments wrong. Ask the vendor for some example code that works so you can check to see if that connects to the server properly. If it does then the error is in the other arguments, if not then it's a problem with your connection to the server.
I'm working on a portion of code that is essentially trying to reduce a list of strings down to a single string recursively.
I have an internal database built up of matching string arrays of varying length (say array lengths of 2-4).
An example input string array would be:
{"The", "dog", "ran", "away"}
And for further example, my database could be made up of string arrays in this manner:
(length 2) {{"The", "dog"},{"dog", "ran"}, {"ran", "away"}}
(length 3) {{"The", "dog", "ran"}.... and so on
So, what I am attempting to do is recursively reduce my input string array down to a single token. So ideally it would parse something like this:
1) {"The", "dog", "ran", "away"}
Say that (seq1) = {"The", "dog"} and (seq2) = {"ran", "away"}
2) { (seq1), "ran", "away"}
3) { (seq1), (seq2)}
In my sequence database I know that, for instance, seq3 = {(seq1), (seq2)}
4) { (seq3) }
So, when it is down to a single token, I'm happy and the function would end.
Here is an outline of my current program logic:
public void Tokenize(Arraylist<T> string_array, int current_size)
{
// retrieve all known sequences of length [current_size] (from global list array)
loc_sequences_by_length = sequences_by_length[current_size-min_size]; // sequences of length 2 are stored in position 0 and so on
// escape cases
if (string_array.Count == 1)
{
// finished successfully
return;
}
else if (string_array.Count < current_size)
{
// checking sequences of greater length than input string, bail
return;
}
else
{
// split input string into chunks of size [current_size] and compare to local database
// of known sequences
// (splitting code works fine)
foreach (comparison)
{
if (match_found)
{
// update input string and recall function to find other matches
string_array[found_array_position] = new_sequence;
string_array.Removerange[found_array_position+1, new_sequence.Length-1];
Tokenize(string_array, current_size)
}
}
}
// ran through unsuccessfully, increment length and try again for new sequence group
current_size++;
if (current_size > MAX_SIZE)
return;
else
Tokenize(string_array, current_size);
}
I thought it was straightforward enough, but have been getting some strange results.
Generally it appears to work, but upon further review of my output data I'm seeing some issues. Mainly, it appears to work up to a certain point...and at that point my 'curr_size' counter resets to the minimum value.
So it is called with a size of 2, then 3, then 4, then resets to 2.
My assumption was that it would run up to my predetermined max size, and then bail completely.
I tried to simplify my code as much as possible, so there are probably some simple syntax errors in transcribing. If there is any other detail that may help an eagle-eyed SO user, please let me know and I'll edit.
Thanks in advance
One bug is:
string_array[found_array_position] = new_sequence;
I don't know where this is defined, and as far as I can tell if it was defined, it is never changed.
In your if statement, when if match_found ever set to true?
Also, it appears you have an extra close brace here, but you may want the last block of code to be outside of the function:
}
}
}
It would help if you cleaned up the code, to make it easier to read. Once we get past the syntactic errors it will be easier to see what is going on, I think.
Not sure what all the issues are, but the first thing I'd do is have your "catch-all" exit block right at the beginning of your method.
public void Tokenize(Arraylist<T> string_array, int current_size)
{
if (current_size > MAX_SIZE)
return;
// Guts go here
Tokenize(string_array, ++current_size);
}
A couple things:
Your tokens are not clearly separated from your input string values. This makes it more difficult to handle, and to see what's going on.
It looks like you're writing pseudo-code:
loc_sequences_by_length is not used
found_array_position is not defined
Arraylist should be ArrayList.
etc.
Overall I agree with James' statement:
It would help if you cleaned up the
code, to make it easier to read.
-Doug
I am not sure what the problem is but I keep receiving this error when I try to use a while statement in my code.
Invalid token 'while' in class,
struct, or interface member
declaration
I want to use a while loop to have something continuously update while a statement is true.
The rest of my code is rather long but whenever I type in the syntax:
while(a<b)
{
//do whatever i want it to do here
}
It gives me that compiler error right off the bat. Not quite sure what the problem is. I am doing this in a C# windows application under the Form1.cs file with all the other event handlers (for buttons and such).
Thanks!
I was unaware that loops had to be placed within a method (fairly new to c#), but I tried it and no errors were returned. Thanks for your help everybody!
Previously, I just had the loop within the main class of the program.
Based on the error, it sounds like the compiler thinks this code is typed directly in the body of a class/struct/interface declaration. Statements while/if/for/etc ... must appear with in a method.
Try moving this code into a method to fix the problem. If it's in a method, you likely have a mismatched brace problem.
There's nothing wrong with the while, it's something above it that's the problem.
Check for mismatched braces and semicolons in a comment or something like that.
C# is not allowed to write code directly into the classes; it is allowed to write only data members and function members directly into the classes.
You can also get this if you have punctuation issues, I got it today when I missing a simple parentheses:
public static string GetPasswordForEnvironment)
should have been:
public static string GetPasswordForEnvironment()
But the error showed up on the first "if" statement later in the function.
C# does not provide writing the for, while or foreach kind of looping statement directly inside the class. These statements should be within a user defined method, main method or constructors.
class Array
{
public static void main(string[] args)
{
int[] n = new int[10]; /* n is an array of 10 integers */
/* initialize elements of array n */
for (int i = 0; i < 10; i++)
{
n[i] = i + 100;
}
/* output each array element's value */
foreach (int j in n)
{
int i = j - 100;
Console.WriteLine("Element[{0}] = {1}", i, j);
}
}
}