"Primary Constructor Body Is Not Allowed" Error - c#

I am getting an error in my code "Primary Constructor Body Is Not Allowed", and can't seem to find a way to fix it. The error occurred because I created a new public method, I have also tried using private and protected methods, but the error was still present. There is someone else on here that asked the same question. The answer that the particular person got leads me to believe that it may be specific to OS X.
Here is my code:
string txt = WordBank ();
string[] words = Moduel.TextToArray("Text.txt");
string compWord = Moduel.Random (words);
Console.WriteLine ("I have chosen a random word, try to guess it one letter at a time");
}
public static void WordBank ();
{
string txt;
Console.WriteLine ("Would you like to " +
"(A) choose 4 letter words " +
"(B) choose 5 letter words " +
"(C) choose 6 letter words " +
"(E) choose 7 lette r words or more?" +
"(F) all words?");
string input = Console.ReadLine ();
if (input = "A")
txt = "4 Letter Words.txt";
else if (input = "B")
txt = "5 Letter Words.txt";
else if (input = "C")
txt = "6 Letter Words.txt";
else if (input = "E")
txt = "7 Letters or More.txt";
else if (input = "F")
txt = "All Words.txt";
else
{
Console.WriteLine("You haven't chosen a valid option, please try again");
Main();
}
return txt;
}
}
}
and here is a picture of the error.
Error Message.

Error is in
public static void WordBank ();
Just remove semicolon from this line
public static void WordBank ()
And your function returned a string value so change function's definition to
public static string WordBank ()

public static void WordBank (); Remove the trailing ; in this line. and also make the return type to string if you have to return a string from the function.
So your method signature will be like the following:
public static string WordBank ()
{
string txt;
//Rest of code comes here
return txt;
}

Currently you have ; after your method declaration:
public static void WordBank ();
{
// code in your method
}
Having semicolon after method declaration is effectively the same like having an empty method body, so in your case the code is the same as
public static void WordBank ()
{
}
{
// code in your method
}
which is incorrect.
In order to fix the issue remove the ; after the method name:
public static void WordBank ()
{
// code in your method
}

There are certainly number of errors in you code.
string txt = WordBank (); where as your function does not return
anything public static void WordBank (); its void.
your code to declare a function public static void WordBank (); is wrong since you need to remove the ; at the end.
inside the function you states return txt; which is not right until your function actually returns something
and thus your code should be
public static string WordBank()
{
return "SomeString"; // in your case txt
}

Thanks everyone for your fast responses, the semicolon was the issue (feel really stupid now :P).

Related

creating global string array through its own class, but still not recognized in different class method C#

Created a simple class with one element, a string [] array and filled it with elements. I want to be able to add and delete elements in this array anywhere in my application, but it is not accessable. been trying variations for two days so coming to the best for help.
enter code here
public static void TestSlots()
{
String currentBehavior = _core.GetVariable("$_current_name", false);
bool success1 = _core.ApiApp().SetDiagOutput("MYWARNING " + currentBehavior + " is");
int indexNumber = MedIntents.medIntents.IndexOf(currentBehavior);
;
if (indexNumber < 0)
{
return;
}
else
{
//Global.MedIntents.RemoveAt(indexNumber);
bool success = _core.ApiApp().SetDiagOutput("MYWARNING " + currentBehavior + " removed");
}
//now check if they asked or hit more than one important entity
return;
}
// Console.WriteLine("Hello World!");
}
internal class MedIntents
{
public string[] medIntents = new string[] {
"any_chills",
"constant_or_intermittent",
"gradual_or_sudden",
"had_them_before",
"how_often",
"howdoesitstart",
"hurt_elsewhere",
"nausea_or_vomitting",
"numbness",
"pain_relief",
"relation_to_food_or_medical",
"scaleofone2ten",
"warning_signs"
};
medIntents is an instance member. You may want to convert it to a static member. To prevent modification, you can add the readonly modifier. – Crafted Pod 2 hours ago

How to implement custom command line & execution

I'm trying to build a custom commandline for my app, i have several basic commands, and i simply use bunch of "if" statements to check what the command is. currently it looks something like this
public void ExecuteCommand()
{
string input = ReadLine(); //gets last string from input
bool isDone = false; //need bool to check whether command was executed or no, by default false.
Match result = Regex.Match(input, #"([^\s]+)"); //to get command name
string commandName = result.Value.ToLower();
string value = Regex.Match(input, #"\s(.*)").Value; //to get its parameter. currently everything after ' ' space.
if (commandName == "close")
{
Close(); isDone = true;
}
//so commandline is separate window, and appendedForm is a main form. in which some functions are executed.
if (commandName == "exit")
{
appendedForm.Close();
}
if (commandName == "spoof")
{
appendedForm.Fn_Spoof();
isDone = true;
}
if(commandName == "spoofstop")
{
appendedForm.Fn_StopCapture();
isDone = true;
}
if(commandName == "scan")
{
appendedForm.Fn_Scan(); isDone = true;
}
if(commandName == "clear")
{
output.Text = "";
WriteLine("Console cleared. Cache is empty.");
//data_lines.Clear();
isDone = true;
}
...
}
So that's basically it. I have a mainForm, and commandline form. string input is typed into commandline, then I check the name of command and execute some function from mainForm.
My question is, what is the best way of implementing such kind of thing? I surely can just continue writing bunch of "if"s, but something tells me that it's not the best way to make it.
I've thought of creating class "Command"
public class Command
{
public string name;
public string description;
public bool hasParameter;
Command()
{
}
}
And storing all commands in some sort of array, but I am not sure how would I use this to call a function from mainForm.
Any ideas are welcome!
You could stuff all commands into a Dictionary<string, someDelegate>; if you can live with all commands having the same return type.
I have used string and set up a few commands.
I make use of the params keyword to avoid the ugly new object[] on each call.
You still need to cast the arguments, unless you can make them all one type. (Which may actually be not such a bad idea, as they all come from an input string..)
Here is an example:
public delegate string cmdDel(params object[] args);
Dictionary<string, cmdDel> cmd = new Dictionary<string, cmdDel>();
Add a few functions:
cmd.Add("clear", cmd_clear);
cmd.Add("exit", cmd_exit);
cmd.Add("add", cmd_add);
cmd.Add("log", cmd_log);
With these bodies:
public string cmd_clear(params object[] args)
{
return "cleared";
}
public string cmd_exit(params object[] args)
{
return "exit";
}
public string cmd_add(params object[] args)
{
return ((int)args[0] + (int)args[1]).ToString();
}
public string cmd_log(params object[] args)
{
StringBuilder log = new StringBuilder();
foreach (object a in args) log.Append(a.ToString() + " ");
return log.ToString();
}
And test:
Console.WriteLine(cmd["clear"]());
Console.WriteLine(cmd["add"]( 23, 42));
Console.WriteLine(cmd["log"]( 23, "+" + 42, "=", cmd["add"]( 23, 42) ));
Console.WriteLine(cmd["exit"]());
cleared
65
23 + 42 = 65
exit
Of course you still need to use (at least) as many lines for setup as you have commands. And also need to do a similar amount of error checking.
But the command processing part can get pretty simple.

How to take a void method that takes readline and runs it though an array and assign it to a string variable

Hello I have a console application that successfully runs input through an array containing Bad Words and if there is a bad word then it will output some text then quits the application. Now I want to see what I can do With DetectBW() Including assigning it to a string Although DetectBW() is a void type and it returns nothing so assigning it to a string isn't possible if it's written like this
EX.
string Name = DetectBW();
Here's my code for further explanation
namespace CleanApp
{
class Application
{
This region contains bad words. I wrote it in otherwise it says a whole list of bad words which wouldn't be good for obvious reason.
//profanityArray()
This region contains numbers 0-318 Including 318
//ProNumArray()
This is the Main method
#region//Main() Put everything thats finished in here to output it to Console Apllication.
static void Main(string[] args)
{
string[] Sarray = profanityArray();
int[] Iarray = ProNum();
// infinite loop that writes "Ask A question." then accepts a line of text from user (DetectBW())
while (true)
{
Console.WriteLine("Ask A question.");
DetectBW();
}
}
#endregion
This is the DetectBW() method it takes PlayerInput()string Method (Console.Readline) and runs it through the profanityArray and detects if PlayerInput() contains any of the bad words in profanityArray.
#region // DetectBW()
static void DetectBW()
{
string PI = PlayerInput();
string[] PIA = profanityArray();
foreach(int i in ProNum())
{
if(PI.ToLower().Contains(PIA[i]))
{
if (PI.ToLower().Contains(" "+PIA[i]+" "))
{
Console.WriteLine(PI + " contains a bad word(s)!");
Console.WriteLine("If you can't be polite then get off!!");
Environment.Exit(0);
break;
}
if (PI.ToLower().Contains(PIA[i]+" ")|| PI.ToLower().Contains(" " + PIA[i]))
{
Console.WriteLine(PI + " contains a bad word(s)!");
Console.WriteLine("If you can't be polite then get off!!");
Environment.Exit(0);
break;
}
}
}
}
#endregion
This region is PlayerInput() it is the string method I was talking about.
#region// PlayerInput()
static string PlayerInput()
{
string S = Console.ReadLine();
return S;
}
#endregion
This is where I plan to to take the DetectBW() run it and take the same playerInput() used in DetectBW() and assign it to a string var for later use.
static void App()
{
Console.WriteLine("What is you name?");
// This is where i need Help!!
}
}
}
So this is my question:
1.
I know that I can't assign a void to a string variable but is there a way to take the same playerInput() used in DetectBW(), so I know that there isn't any bad words in it, and assign it to a name string variable.

Calling string from another method

I have a problem with calling a string from another method from the same script. I'm not sure if this is possible with C#
Sorry I'm new to C# but I used to do this in Objective-C so maybe its possible here?
So, the below code is the method I'm trying to use that string into.
This method checked if a message is passed in the game and execute the code.
void HandleMessage(string message, string metadata)
{
if (message == "UnlockName")
{
}
}
This is the method that contains the string needed (txt)
void OutputText( string txt ) {
//string firstName = lastLoadedLevel.contact.name.Split(new char[] { ' ' })[0];
//txt = txt.Replace("C:", firstName + ":");
txt = txt.Replace("D:", "D's name:");
txt = txt.Replace("[name]", PlayerPrefs.GetString("name"));
chat.AddText( txt, delegate {
options.gameObject.SetActive( true );
} );
}
Right now it contains (txt.Replace) which happens automaticlly throughout the text output.
I want to do the same in (void HandleMessage) to only do the replace code when the message "UnlockName" is passed.
The 2 commented lines here are what I need to use but I don't know how to use them in the first method.
Any help would be great :)
Thank you in advance.
Something like this maybe:
string HandleMessage(string message, string txt)
{
if (message == "UnlockName")
{
string firstName = lastLoadedLevel.contact.name.Split(new char[] { ' ' })[0];
return txt.Replace("C:", firstName + ":");
}
}
void OutputText(string txt, string message)
{
txt = HandleMessage(message, txt);
txt = txt.Replace("D:", "D's name:");
txt = txt.Replace("[name]", PlayerPrefs.GetString("name"));
chat.AddText(txt, delegate
{
options.gameObject.SetActive(true);
});
}
Might need some tweaking, I made some guesses on how you might be using things.
If nothing else, it should give you the concept of one way to pass strings in and back out of a method. You could also keep the void signature and pass in the string to be manipulated as a ref parameter.

Using if to compare strings c#

I am trying to compare strings then have it write hi if the strings are equal.
But whenever I enter AS I get nothing AS being the string i want to compare my input against.
Here is my code.
using System;
namespace testing121
{
class MainClass
{
public static void Main (string[] args)
{
long vrt;
bool run;
string pass = ("AS");
run = true;
string vrt2;
while (run)
{
if (long.TryParse (Console.ReadLine (), out vrt)) {
vrt2 = Convert.ToString (vrt);
if (String.Equals (pass, vrt2) ) {
Console.WriteLine ("Hi");
}
}
}}}}
This code just doesn't make sense. You're entering AS but then checking if it can be converted to a long as part of your condition for equality. Just do this;
public static void Main (string[] args)
{
string pass = "AS";
if (Console.ReadLine() == pass)
Console.WriteLine("hi");
}
Then, if you want to put that in a loop or whatever go for it. But I recommend starting with the simplest most basic thing. When you run this program and enter AS it will print hi
Because when you check your if
(long.TryParse
(Console.ReadLine (), out
vrt)) the result of the TryParse is always False as you don't provide a number as long.
And the console will not write you Hi.
You can also do this...
string pass = "AS";
if (pass.Equals(Console.ReadLine()))
{
Console.WriteLine("hi");
}

Categories

Resources