Identifier Expected c# for unknown reason - c#

Trying to make a simple app which will ask a few questions.
But for some reason, my AskQuestion function doesn't work.
I plan on adding an easily swap able database later which is why I'm trying to take a slightly more modular approach and as I am a beginner I am unsure what I did wrong. The only errors are in line 21 for the AskQuestion class.
Errors are:
CS1001 Identifier Expected
CS1514 { expected
CS1513 } expected
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Quiz
{
class Program
{
// Question Base
class Question
{
public String question = "Empty Question";
public String correctanswer = "Empty Answer";
public String givenanswer = "Empty Answer";
public String response = "Empty Response.";
public bool cleared = false;
}
// Ask Base
class void AskQuestion(Question Q)
{
while (Q.cleared == false)
{
Console.WriteLine(Q.question);
Q.givenanswer = Console.ReadLine();
Q.givenanswer.ToLower();
if (Q.givenanswer == Q.correctanswer)
{
Console.WriteLine(Q.response);
Q.cleared = true;
}
else
{
Console.WriteLine("Wrong. Try again.");
}
}
}
// Main Function
void Main(string[] args)
{
string Name;
Console.WriteLine("Welcome challenger! You're going to have a good time.");
Console.WriteLine("Make sure you use proper grammar. Or you may be stuck for no reason.");
Console.WriteLine("What is your name challenger?");
Name = Console.ReadLine();
Console.WriteLine("Welcome {0} to the challenge. I wish you best of luck. You will need it.",Name);
Question Q1 = new Question();
Q1.question = "What is the color of the sun?";
Q1.correctanswer = "White";
Q1.response = "Correct. Despite the fact it appears Yellow on earth, if you observe the sun from space, you would see it's true color. White.";
AskQuestion(Q1);
Q1.cleared = true;
Console.WriteLine("Nice little warmup. But, lets get a bit serious.");
}
}
}

change this
class void AskQuestion(Question Q)
to
void AskQuestion(Question Q)
This should be a method. The keyword class tells the compiler you want to create a inner class inside the out class Program

Q.givenanswer.ToLower(); doesn't make Q.givenanswer lowercase - it returns a new lowercase string which you need to assign to a variable, or just `Q.givenanswer = Q.givenanswer.ToLower();

Related

Getting error: Cannot implicitly convert type 'string' to 'int'

I'm new to coding. I am trying to improve myself by making simple coding. I just encountered such error while writing a code to retrieve data from user.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FuelCalc
{
internal class Program
{
static void Main(string[] args)
{
//readline
Console.WriteLine("Lütfen size hitap edebilmem için adınız ve soyadınızı giriniz...");
string namesurn= Console.ReadLine();
Console.WriteLine("Merhaba " + namesurn +" lütfen aracınızın ortalama yakıt tüketimini giriniz...");
int yakit = Console.ReadLine();
Console.ReadLine();
}
}
}
What you could try is adding a loop to repeat until the user enters a number. The int.TryParse method will return true if the string returned from Console.ReadLine() can be interpreted as an int and you will have a value for yakit in that case. Otherwise, ask the user to try again.
(I'm relying on Google Translate here leave me a comment if I did something wrong!)
static void Main(string[] args)
{
//readline
Console.WriteLine("Lütfen size hitap edebilmem için adınız ve soyadınızı giriniz...");
string namesurn = Console.ReadLine();
Console.WriteLine("Merhaba " + namesurn + " lütfen aracınızın ortalama yakıt tüketimini giriniz...");
// Loop until a valid int is received.
while(true)
{
if(int.TryParse(Console.ReadLine(), out int yakit))
{
Console.WriteLine($"{yakit} alınan");
break;
}
else
{
Console.WriteLine("Numara gerekli");
}
}
Console.ReadLine();
}
You may want to consider float or double instead of int in case the user enters a decimal point character like "40.9" in which case you could substitute:
float.TryParse(Console.ReadLine(), out float yakit)

for loop and string slicing gives unexpected output

i am starting to learn C#, my first language i learned is Python and i switched to Visual Studio Code for it from Pycharm.
I am trying to code a simple TicTacToe as exercise, when i loop trough my TicTacToe grid to see if one of the empty fields marked with numbers is still avaliable, i get an unexpected output.
The expected output would be 1-9, but its not, i am not allowed to post images so not sure how to say/show it.
When i use char as data type the correct value seems to be there in '' as second value, but how do access it?
in both cases comparision operator do not yield the expected results!
using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
namespace CSharp_Shell
{
public static class Programm
{
static int meow = 1;
static string board_roof = "-------";
static string board_mid1 = "|1|2|3|";
static string board_mid2 = "|4|5|6|";
static string board_mid3 = "|7|8|9|";
static string board_all_default = board_roof + Environment.NewLine + board_mid1 + Environment.NewLine +board_mid2 + Environment.NewLine +board_mid3 + Environment.NewLine + board_roof;
public static void Main(string[] args) {
Acces_board2(meow);
}
public static void Acces_board2(int lfm) {
for(int gas=0; gas<board_all_default.Length; gas++) {
bool result = char.IsNumber(board_all_default[gas]);
if (result) {
Console.WriteLine($"{board_all_default[gas]} , {lfm}");
if(lfm < board_all_default[gas]) {
Console.WriteLine($"True");
}
}
}
}
}
}
doesnt matter if i use
if (lfm < board_all_default[gas])
or
int checkme = board_all_default[gas];
if (lfm < checkme)
it never works, that would be no issue in python, i have no clue whats happening

ml.net sentiment analysis warning about format errors & bad values

I've been having a problem with my ml.net console app. This is my first time using ml.net in Visual Studio so I was following this tutorial from microsoft.com, which is a sentiment analysis using binary classification.
I'm trying to process some test data in the form of tsv files to get a positive or negative sentiment analysis, but in debugging I'm receiving warnings there being 1 format error and 2 bad values.
I decided to ask all you great devs here on Stack to see if anyone can help me find a solution.
Here's an image of the debugging below:
Here's the link to my test data:
wiki-data
wiki-test-data
Finally, here's my code for those who what to reproduce the problem:
There's 2 c# files: SentimentData.cs & Program.cs.
1 - SentimentData.cs:
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.ML.Runtime.Api;
namespace MachineLearningTut
{
public class SentimentData
{
[Column(ordinal: "0")]
public string SentimentText;
[Column(ordinal: "1", name: "Label")]
public float Sentiment;
}
public class SentimentPrediction
{
[ColumnName("PredictedLabel")]
public bool Sentiment;
}
}
2 - Program.cs:
using System;
using Microsoft.ML.Models;
using Microsoft.ML.Runtime;
using Microsoft.ML.Runtime.Api;
using Microsoft.ML.Trainers;
using Microsoft.ML.Transforms;
using System.Collections.Generic;
using System.Linq;
using Microsoft.ML;
using Microsoft.ML.Data;
using System.Threading.Tasks;
namespace MachineLearningTut
{
class Program
{
const string _dataPath = #".\Data\wikipedia-detox-250-line-data.tsv";
const string _testDataPath = #".\Data\wikipedia-detox-250-line-test.tsv";
const string _modelpath = #".\Data\Model.zip";
static async Task Main(string[] args)
{
var model = await TrainAsync();
Evaluate(model);
Predict(model);
}
public static async Task<PredictionModel<SentimentData, SentimentPrediction>> TrainAsync()
{
var pipeline = new LearningPipeline();
pipeline.Add(new TextLoader (_dataPath).CreateFrom<SentimentData>());
pipeline.Add(new TextFeaturizer("Features", "SentimentText"));
pipeline.Add(new FastForestBinaryClassifier() { NumLeaves = 5, NumTrees = 5, MinDocumentsInLeafs = 2 });
PredictionModel<SentimentData, SentimentPrediction> model = pipeline.Train<SentimentData, SentimentPrediction>();
await model.WriteAsync(path: _modelpath);
return model;
}
public static void Evaluate(PredictionModel<SentimentData, SentimentPrediction> model)
{
var testData = new TextLoader(_testDataPath).CreateFrom<SentimentData>();
var evaluator = new BinaryClassificationEvaluator();
BinaryClassificationMetrics metrics = evaluator.Evaluate(model, testData);
Console.WriteLine();
Console.WriteLine("PredictionModel quality metrics evaluation");
Console.WriteLine("-------------------------------------");
Console.WriteLine($"Accuracy: {metrics.Accuracy:P2}");
Console.WriteLine($"Auc: {metrics.Auc:P2}");
Console.WriteLine($"F1Score: {metrics.F1Score:P2}");
}
public static void Predict(PredictionModel<SentimentData, SentimentPrediction> model)
{
IEnumerable<SentimentData> sentiments = new[]
{
new SentimentData
{
SentimentText = "Please refrain from adding nonsense to Wikipedia."
},
new SentimentData
{
SentimentText = "He is the best, and the article should say that."
}
};
IEnumerable<SentimentPrediction> predictions = model.Predict(sentiments);
Console.WriteLine();
Console.WriteLine("Sentiment Predictions");
Console.WriteLine("---------------------");
var sentimentsAndPredictions = sentiments.Zip(predictions, (sentiment, prediction) => (sentiment, prediction));
foreach (var item in sentimentsAndPredictions)
{
Console.WriteLine($"Sentiment: {item.sentiment.SentimentText} | Prediction: {(item.prediction.Sentiment ? "Positive" : "Negative")}");
}
Console.WriteLine();
}
}
}
If anyone would like to see the code or more details on the solution, ask me on the chat and I'll send it. Thanks in advance!!! [Throws a Thumbs Up]
I think I got a fix for you. A couple of things to update:
First, I think you got your SentimentData properties switched to what the data has. Try changing it to
[Column(ordinal: "0", name: "Label")]
public float Sentiment;
[Column(ordinal: "1")]
public string SentimentText;
Second, use the useHeader parameter in the TextLoader.CreateFrom method. Don't forget to add that to the other one for the validation data, as well.
pipeline.Add(new TextLoader(_dataPath).CreateFrom<SentimentData>(useHeader: true));
With those two updates, I got the below output. Looks like a nice model with an AUC of 85%!
Another thing that helps with text type datasets is indicating that the text has quotes:
TextLoader("someFile.txt").CreateFrom<Input>(useHeader: true, allowQuotedStrings: true)
There is bad formated value on 252 and 253 rows. May me there fields wich contains the delimiter charachter.
If you post code or sample data we can be more precise.

C#, basic error

So I am making a super basic (I'm in my second week of learning C# so please excuse my ignorance) program that takes a string input from a user and outputs the string backwards. I have copied the book to a T in regards to a majority of it but I have noticed spelling errors in some of their code so I don't have a lot of faith in what they are showing. My compiler is giving me an error with WriteLine and ReadLine and I don't understand why as the book says it works. This is the error I am getting;
"WriteLine does not exist in the current context" same with "ReadLine"
My code;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
static class funcStrings
{
public static string ReverseString(string s)
{
char[] arr = s.ToCharArray();
Array.Reverse(arr);
return new string(arr);
}
}
class runProgram
{
class Program
{
static void Main()
{
string name;
WriteLine("Enter your name to be reversed ");
name = ReadLine();
Console.WriteLine(funcStrings.ReverseString(name));
}
}
}
}
Thanks for any guidance here
You just need to add Console. in front:
Console.WriteLine("Enter your name to be reversed ");
name = Console.ReadLine();
You can add such namespace:
using static System.Console;
This brings all the static members from the System.Console class into scope, so that you don't need to prefix them with Console. It is a C# 6 feature, and useful when accessing many members in a static class. See relevant documentation.
The problem is probably that it should be Console.WriteLine and Console.ReadLine.
Currently it is:
static void Main()
{
string name;
WriteLine("Enter your name to be reversed ");
name = ReadLine();
Console.WriteLine(funcStrings.ReverseString(name));
}
You need to add a Console.WriteLine("Enter your name to be reversed"):

Use method to Return value int in C#

I'm taking a programming class in c# and it is our first week and I'm trying to work ahead a little. To that end, I am trying to rework one of our class labs and am stuck with my 'GetInt' method.
Ideally, the GetInt method (line 50) takes in a string (Enter a number) and returns the number as an int so i can then use it to do some math. Currently line #24 turns the test error 'Cannot implicity convert type 'int' to 'string'.
Any help is appreciated. I am very much a newb, so please don't assume i know anything.
Thank you.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace lec022_If_statement_int
{
class Program
{
//Set to public so it is visible
//void because it returns nothing
//Play is a method within the class Program I've added
public void Play()
{
DisplayStr("Lecture 2c | If Statements with ints");
DisplayReturns();
DisplayStr("Welcome to Dunut King");
DisplayReturns();
//Collect User Name
//GetString converts to lower, trims
String numDonuts = GetInt("How many donuts would you like?: ");
DisplayReturns();
//Display welcome
Console.WriteLine("You asked for " + numDonuts + " donuts.");
DisplayReturns();
DisplayReturns();
DisplayStr("Have a great Day!");
}
//MaxBox 2.0
public void DisplayStr(String StrTxt)
{ Console.Write(StrTxt); }
public void DisplayReturns()
{ Console.Write("\n\n"); }
public string GetString(String StrVar)//note - using strings here
{
Console.Write(StrVar);
return Console.ReadLine().ToLower().Trim();
}
public int GetInt(string intVar)//note - using ints here
{
Console.Write(intVar);
return int.Parse(Console.ReadLine());
}
//Initiate Program
static void Main(string[] args)
{
Program myProgram = new Program();
myProgram.Play();
Console.Read();
}
}
}
Your GetInt method returns int. So you need to change from
String numDonuts = GetInt("How many donuts would you like?: ");
to
int numDonuts = GetInt("How many donuts would you like?: ");
The problem is that the method GetInt returns int.
And you're trying to assign its return value to this String variable on line 24.
String numDonuts
You cannot do this.
Change the first word on line #24 from 'String' to 'int' because I am asking for an int not a string.
Your problem is there:
String numDonuts = GetInt("How many donuts would you like?: ");
You try to set int value to string variable.
change to
var numDonuts = GetInt("How many donuts would you like?: ");
Your GetInt method returns integer type so you should use an integer type to store it, not a string.
Here is the fixed code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace lec022_If_statement_int
{
class Program
{
//Set to public so it is visible
//void because it returns nothing
//Play is a method within the class Program I've added
public void Play()
{
DisplayStr("Lecture 2c | If Statements with ints");
DisplayReturns();
DisplayStr("Welcome to Dunut King");
DisplayReturns();
//Collect User Name
//GetString converts to lower, trims
int numDonuts = GetInt("How many donuts would you like?: ");
DisplayReturns();
//Display welcome
Console.WriteLine("You asked for " + numDonuts + " donuts.");
DisplayReturns();
DisplayReturns();
DisplayStr("Have a great Day!");
}
//MaxBox 2.0
public void DisplayStr(String StrTxt)
{ Console.Write(StrTxt); }
public void DisplayReturns()
{ Console.Write("\n\n"); }
public string GetString(String StrVar)//note - using strings here
{
Console.Write(StrVar);
return Console.ReadLine().ToLower().Trim();
}
public int GetInt(string intVar)//note - using ints here
{
Console.Write(intVar);
return int.Parse(Console.ReadLine());
}
//Initiate Program
static void Main(string[] args)
{
Program myProgram = new Program();
myProgram.Play();
Console.Read();
}
}
}
I've just tested the program. You enter a number and you get a response. Works nicely. (For it's simple purpose :-) )

Categories

Resources