Can't seem to print a method in c# [duplicate] - c#

This question already has answers here:
C# Creating and using Functions
(11 answers)
Closed 4 years ago.
I am trying to make a simple program that makes a list of words then it picks a random word and then it prints that word. Everything works but I just can't seem to make the program print the word. This is my code so far.
using System;
using System.Collections.Generic;
namespace Hangman
{
class Program
{
List<String> words = new List<String> { "cat", "police", "conjuring", "sand", "hoppleflink", "defenestrait", "cumberground", "sexy shreck" };
public string PickRandom()
{
var random = new Random();
var wordCount = words.Count;
var randomNum = random.Next(wordCount);
var randomWord = words[randomNum];
return randomWord;
}
static void Main(string[] args)
{
Console.WriteLine();
}
}
}

To make your code work, you need to print a value rather than nothing, as you currently are.
At the moment, your words field and PickRandom method are instance members, so Main (a static method) cannot use them without an instance of Program. So, first, we'll create an instance of Program:
Program program = new Program();
Then we'll take a random word:
string word = program.PickRandom();
And finally we'll write it:
Console.WriteLine(word);
Putting it all together:
static void Main(string[] args)
{
Program program = new Program();
string word = program.PickRandom();
Console.WriteLine(word);
// keep the console open after the code has executed by waiting for a keypress
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
You can read about static vs instance members here.
You'll probably run up against an issue with Random soon - if you call your PickRandom method too frequently, you'll find that you get the same value repeated. The reason why is explained in this post. TL;DR: The seed value is based on time, so if you create two instances of Randomat the exact same time, you'll get the same seed value.

Related

Error "Missing closing curly bracket" while all curly brackets are closed?

I am trying to code a card game, and I'm making a shuffling system using a function, however it's telling me I need a closing bracket while all my brackets are closed. It's also asking me for an end-of-file or namespace definition. I'm using an online editor (dotnetfiddle.net) to edit this code, if that changes anything.
Here's my current code-
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
Console.WriteLine("Hello World");
List<string> shuffle(List<string> l) { //ERROR 1: } expected
int count = l.Count-1;
List<string> ret = new List<string>();
int ind = 0;
Random rng = new Random();
string card = null;
while (count > -1) {
ind = rng.Next(0, count);
card = l[ind];
l.RemoveAt(ind);
ret.Add(card);
card = null;
count--;
}
return ret;
}
List<List<string>> playerHands = new List<List<string>>();
//💧🔥🌀🌱 (copypaste symbols)
List<string> deck = new List<string> {"1💧", "2💧", "3💧", "4💧", "5💧", "6💧", "7💧", "8💧", "9💧", "1🔥", "2🔥", "3🔥", "4🔥", "5🔥", "6🔥", "7🔥", "8🔥", "9🔥", "1🌀", "2🌀", "3🌀", "4🌀", "5🌀", "6🌀", "7🌀", "8🌀", "9🌀", "🌱1", "🌱2", "🌱3", "🌱4", "🌱5", "🌱6", "🌱7", "🌱8", "🌱9"};
List<string> sDeck = new List<string> {"R🔄", "S❌", "D🔳", "X⛈", "+✨", "A🌕", "A🌑"};
List<string> vDeck = new List<string> {"V◆", "V◇", "V◈"};
}
}//ERROR 2: Namespace, type, or end-of-file expected
Maybe it is related to the C# version you used.
Local functions are only allowed when using C# 7.
When I pasted your code in VS 2019, the compilation succeeded.
The only warning I have, is related to the function shuffle() that is declared but never used.
Also, always put your class in a namespace.

How to define separate function in C#?

Since the .NET version has been updated, there is no need to write entire C# code just to print 'Hello World!'. Just Console.WriteLine(); is enough. But what I could not understand, is how to define a new function outside Main()?
If I want to develop a separate function outside Main(), do I need to write entire code including using System; and namespaces and Main() function? I am talking about updated version which is C# v10.
Please, do enlighten me!
I hope this question is not much lengthy and you got idea regarding the problem.
Here is the code for your reference:
class Program
{
public static void Main(string[] args)
{
string? theWord;
System.Console.WriteLine("Enter the word");
theWord = Console.ReadLine();
System.Console.WriteLine("original string: " + theWord);
System.Console.WriteLine("middle character of " + theWord + " is " + test(theWord));
}
public static string test(string theWord)
{
int i = 1 - theWord.Length % 2;
return theWord.Substring(theWord.Length / 2-i, 1+i);
}
}
There are two important things to understand here:
Firstly, top-level statements and implicit using directives are entirely different features. So you can declare a class as normal, but still omit the using directives. Likewise if you don't want to declare a namespace, you don't have to - although these days you could just use a file-scoped namespace declaration, e.g. namespace MyNamespace; without indenting everything.
Secondly, even with top-level statements, you can write methods... but they're effectively local methods within the Main method, and come with all the restrictions that imposes (e.g. no overloading). Note that even with top-level statements for your entry point, you can still declare other classes elsewhere - it would be entirely reasonable to have a brief Program.cs using top-level statements just to get everything going, but use "regular" C# elsewhere in the project. Indeed, that's how the ASP.NET Core templates work these days.
As an example, given the sample code, you could write (slightly amended for naming and to avoid warnings):
System.Console.WriteLine("Enter the word");
string? input = Console.ReadLine();
if (input is null)
{
Console.WriteLine("No input");
return;
}
System.Console.WriteLine($"Original string: {input}");
System.Console.WriteLine($"Middle character of {input} is {GetMiddle(input)}");
string GetMiddle(string input)
{
int i = 1 - input.Length % 2;
return input.Substring(input.Length / 2 - i, i + 1);
}
In this particular case you don't actually need the parameter for the method - input would be captured anyway, because GetMiddle is a local method.
You can write that like a normal method.
using System;
Console.WriteLine("Hello World");
display();
static void display()
{
Console.WriteLine("from display");
}

inserting into index location of a text file if a string does exist inside the line, if the string doesn't exist, still write line as it was

The program is supposed to look for a string in a line, and if it finds the string, it will make the inserts after meeting the condition inside the textfile. Currently, when I run this program it is now simply giving me a blank console. Previously, I had it just reading all the lines properly and could make inserts only if I remove them first but it messed the indexing up and ultimately did not give me the result I wanted. The logic is fairly straightforward, if you see any problems please share your thoughts. Please and thanks. I am very confused why this is having problems and not working.
using System.IO;
using System.Globalization;
using System.Diagnostics;
using System.Text;
using System.Linq;
using System.Linq.Expressions;
namespace Masker
{
class Program
{
public static void Main(string[] args)
{
Console.WriteLine();
string path = #"\file1.txt";
ReadLines(path)
}
public static void ReadLines(string path)
{
int counter = 0;
var text = new StringBuilder();
foreach (string s in File.ReadAllLines(path))
{
counter += 1;
if (s.Contains("000INDEX"))
{
text.AppendLine(s.Insert(60, "#"));
}
else if (s.Contains("001PRTBNR"))
{
text.AppendLine(s.Insert(60, "#").Insert(119,"#").Insert(120,"#").Insert(121, "#"));
};
text.AppendLine(s);
//Console.Write(text.ToString());
}
Console.Write(text.ToString());
}
}
}
The last two blocks of your if/else statement will never be executed.
If the execution reaches the third check
else if (s.Contains("000INDEX"))
that will always be true. Because if it wasn't, then the first check
if (!s.Contains("000INDEX"))
would have already been true.
But the biggest problem is that if the line contains "000INDEX", your while loop becomes and infinite loop. You never leave it. That is probably the reason why you end up with a blank console.

c# ERROR : The modifier 'private ' is not valid for this item [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
It doesn't matter what modifier I put on the front of the function(I've tried with public, private and even protected), I always receive an error, the same error. The code is clean only after I delete the modifier and I left the function "Array()" without one. Can someone look at my code and explain to me what is happening please, I am new to c#, and also new to asking help, so please excuse every mistake I've made so far.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
public void Array()//nu se pune in interiorul functiei void Main (), deoarece va forma nesting, si ne va da eroare la compilare.
{
int[] intArray;
intArray = new int[3];//all values will be 3
var doubleArray = new[] { 34.23, 10.2, 23.2 };
//var arrayElement = doubleArray[0];
//doubleArray[1] = 5.55;
for (var i = 0; i < intArray.Length; i++)
{
Console.WriteLine(intArray[i]);
}
}
}
}
}
I've posted the code and the image of it down below.
In this image you can see the code
You have a nested function, in C# these are called local functions and don't have scope. so you need to remove the access modifier, for example:
public static void PrintHelloWorld()
{
string GetName()
{
return "world";
}
Console.WriteLine($"Hello {GetName()}");
}
You are creating a nested method (also called local function).
Nested methods may not have access modifiers. They are only accessible from within this method.
For reference: https://learn.microsoft.com/dotnet/csharp/programming-guide/classes-and-structs/local-functions
You are putting your private function inside a static function. Remove the private.
Move the function out of the Main function. Also you should mark it as static and then use it as you intend. This in case you don't want a nested method as it is already answered.

C# not connecting to R using RDotNet

I am trying to interface C# to R using RDotNet.
The following code is wants R to calculate the sum of two numbers and C# to get the result back and display it in the command window.
using System;
using RDotNet;
namespace rcon
{
class Program
{
static void Main(string[] args)
{
string dllPath = #"C:\Program Files\R\R-3.1.0\bin\i386";
REngine.SetDllDirectory(dllPath);
REngine.CreateInstance("RDotNet");
//REngine engine = REngine.GetInstanceFromID("RDotNet");
using (REngine engine = REngine.GetInstanceFromID("RDotNet"))
{
var x = engine.Evaluate("x <- 1 + 2");
Console.WriteLine(x);
}
}
}
}
but when I try to send the command to R and get back the calue in x I got an error:
"InvalidOperationException was unhandled"
"Operation is not valid due to the current state of the object."
If I explore the object "engine" I see that IsRunning=false.
Can this be the problem? And how can I fix this in order to be able to interface to R?
It looks like you have outdated version of R.NET.
From R.NET project documentation
R.NET 1.5.10 and subsequent versions include significant changes
notably to alleviate two stumbling blocks often dealt with by users:
paths to the R shared library, and preventing multiple engine
initializations.
You can update your R.NET using NuGet manager from Visual Studio. See the same documentation page for detals.
Here is code sample from the same documentatin page - note that initialization of REngine is significantly simpler now (as now Rengine looks at the Registry settings set up by the R installer):
REngine.SetEnvironmentVariables(); // <-- May be omitted; the next line would call it.
REngine engine = REngine.GetInstance();
// A somewhat contrived but customary Hello World:
CharacterVector charVec = engine.CreateCharacterVector(new[] { "Hello, R world!, .NET speaking" });
engine.SetSymbol("greetings", charVec);
engine.Evaluate("str(greetings)"); // print out in the console
string[] a = engine.Evaluate("'Hi there .NET, from the R engine'").AsCharacter().ToArray();
Console.WriteLine("R answered: '{0}'", a[0]);
Console.WriteLine("Press any key to exit the program");
Console.ReadKey();
engine.Dispose();

Categories

Resources