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");
}
Related
C# newbie. Trying to make a simple gradebook program where user:
Enters names of students until 'done' is entered
Enter grades for each user, then calculate average
Part 2 works, but my problem is with part one--you have to hit enter twice to commit the name to the list. For instance, if I enter Bob, Lisa, Kevin, Jane--only Bob and Kevin would make it in--the second line (even if you type something) acts as the line where the console.read is committed to the list.
Here's my code:
using System;
using System.Collections.Generic;
using System.Linq;
namespace Csharp
{
class MainClass
{
static List<string> mylist = new List<string> { };
public static void Main(string[] args)
{
UserInput();
GradeEnter();
}
public static void UserInput()
{
Console.WriteLine("Enter Some names (type 'done' when finished)");
do
{
mylist.Add(Console.ReadLine());
} while (!Console.ReadLine().Equals("done"));
}
public static void GradeEnter()
{
foreach (var x in mylist)
{
List<int> myInts = new List<int>();
Console.WriteLine("\nEnter grades for {0}, (enter any letter when done)", x);
while (Int32.TryParse(Console.ReadLine(), out int number))
{
myInts.Add(number);
}
Console.Write("Average is ");
Console.Write(myInts.Average());
}
}
}
}
Any help on this would be much much appreciated!
Thanks
You are calling ReadLine twice.
You can try this instead:
public static void UserInput()
{
Console.WriteLine("Enter Some names (type done to exit)");
string name = Console.ReadLine();
while (!name.Equals("done"));
{
mylist.Add(name);
name = Console.ReadLine();
}
}
Another way of doing the same
public static void UserInput()
{
Console.WriteLine("Enter Some names (type done to exit)");
while (true);
{
string name = Console.ReadLine();
if (name == "done")
{
// This will stop the while-loop
break;
}
mylist.Add(name);
}
}
Now let's analyze what your code is doing
do
{
// Read line and add it to the list. Even if the user writes "done"
mylist.Add(Console.ReadLine());
// Read the console again, if the user enters done, exit. But if the user enters other name, you are discarding it, you are not adding it to the list
} while (!Console.ReadLine().Equals("done"));
Some test cases using your code:
1. Peter <- gets added to the list
2. Lucas <- does not get added to the list, just checks if it is done
3. Mario <- gets added to the list
4. Juan <- again, just checking if it is done, so not added to the list
5. done <- It is treated like a name, so it will be added to the list
6. done <- now it will finish :)
Read name once and then either add it to myList or stop looping:
public static void UserInput() {
Console.WriteLine("Enter Some names (type done to exit)");
for (string name = Console.ReadLine(); !name.Equals("done"); name = Console.ReadLine())
mylist.Add(name);
}
Thanks for everyone's help. I ended up using a combination of while(true) and an if statement:
Console.WriteLine("Enter some names (type 'done' when finished)");
do
{
string name = Console.ReadLine();
if (!name.Equals("done"))
{
mylist.Add(name);
}
else
break;
} while (true);
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.
We are currently working on a logging solution and have implemented an extension method call 'Log'. When writing to the log file, we would ideally like to write the original variable name (rather than the variable name used in the extension method).
What we are currently having to do for this is:
public void DoSomeWork()
{
String testString = "Hey look I'm a string!";
testString.Log("testString value");
}
With the extention method:
public static String Log(this String valueToStore, String name)
{
// The logging code which uses the 'name' parameter
}
The issue here is that it becomes difficult to read on longer lines of code and looks clustered. What would be ideal is this:
public void DoSomeWork()
{
String testString = "Hey look I'm a string!";
testString.Log();
}
With the extension method:
public static String Log(this String valueToStore)
{
// The logging code which is able to retrieve the
// value 'testString' from the 'valueToStore' value
}
Is this at all possible by using Reflection? I'm aware of the nameofoption, but that only returns the string 'valueToStore' when used in the extension method.
Well, short answer is no. The variable names are not guaranteed to persist after compilation in unchanged form. That information would have to be somehow persisted (for example by the use of nameof()). Also, the variable name might not exist ("test".GetVarName()).
The long answer is: yes, possibly, but it's one of the most ridiculous things I've created in my life:
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
namespace Test1
{
class Program
{
static void Main(string[] args)
{
var myVarName = "test";
myVarName.Test();
Console.ReadKey();
}
}
static class Extensions
{
public static void Test(
this string str,
[System.Runtime.CompilerServices.CallerMemberName] string memberName = "",
[System.Runtime.CompilerServices.CallerFilePath] string sourceFilePath = "",
[System.Runtime.CompilerServices.CallerLineNumber] int sourceLineNumber = 0
)
{
var relevantLine = File.ReadAllLines(sourceFilePath)[sourceLineNumber-1];
var currMethodName = MethodInfo.GetCurrentMethod().Name;
var callIndex = relevantLine.IndexOf(currMethodName + "()");
var sb = new Stack<char>();
for (var i = callIndex - 2; i >= 0; --i)
{
if (Char.IsLetterOrDigit(relevantLine[i]))
{
sb.Push(relevantLine[i]);
}
}
Console.WriteLine(new String(sb.ToArray()));
}
}
}
C# 10 has CallerArgumentExpressionAttribute that will do just that
public static void PrintNameAndValue(
this object obj,
[System.Runtime.CompilerServices.CallerArgumentExpression("obj")] string callerExp = ""
)
{
Console.WriteLine(callerExp + " = " + obj.ToString());
}
It'll capture the entire expression passed:
public void TestPrintNameAndValue()
{
string mystring = "test";
int myint = 5;
mystring.PrintNameAndValue(); // mystring = test
myint.PrintNameAndValue(); // myint = 5
(myint + 10).PrintNameAndValue(); // myint + 10 = 15
mystring.ToUpper().PrintNameAndValue(); // mystring.ToUpper() = TEST
}
You can use an Expression to achieve that, but performance-wise it may not be the best option:
public static void Log<T>(Expression<Func<T>> expr)
{
var memberExpr = expr.Body as MemberExpression;
if (memberExpr == null)
return;
var varName = memberExpr.Member.Name;
var varData = expr.Compile()();
// actual logging
...
}
Usage:
var test = "Foo";
Log(() => test);
Alternatively, if you're using C# 6.0, it can get a bit better using the nameof operator:
test.Log(nameof(test));
A better solution would be one that is leveraging the compiler abilities (specifically, the "Roslyn" compiler) and provide the member name on compile time.
Not really an answer, more of a pointer, but you could try doing something with your application that you're using(e.g. visual studio) instead of doing it in code. What I mean is make it rewrite everything that looks like [variable].Log(); to [variable].Log([variable])
I am pretty sure that there has to be some weird macro or plugin which does this for you before compiling.
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).
Example:
public static string BoolToYesOrNo(this bool text, out string outAsHtmlName)
{
string[] choices = { "Yes", "No", "N/A" };
switch (text)
{
case true: outAsHtmlName = choices[0]; return choices[0];
case false: outAsHtmlName = choices[1]; return choices[1];
default: outAsHtmlName = choices[2]; return choices[2];
}
}
throws an exception that no overload ... takes 1 argument, altough i am using 2 arguments.
myBool.BoolToYesOrNo(out htmlClassName);
this is the exact exception: CS1501: No overload for method 'BoolToYesOrNo' takes 1 arguments.
This works fine for me with your code:
static void Main()
{
bool x = true;
string html;
string s = x.BoolToYesOrNo(out html);
}
Most likely, you are missing using directive to the namespace of the type that declares BoolToYesOrNo, so add:
using The.Correct.Namespace;
to the top of your code file, where:
namespace The.Correct.Namespace {
public static class SomeType {
public static string BoolToYesOrNo(this ...) {...}
}
}
I tried your code this way and it works without any exceptions, the only thing I would point out if you are giving a parameter with out then you don't need the method to do any return of string
bool b = true;
string htmlName;
string boolToYesOrNo = b.BoolToYesOrNo(out htmlName);
This is what I did to test this out:
I created a new C# Console Application (framework 4.5) in Visual Studio 2012 RC
Changed program.cs to look like this
(omitting usings)
namespace ConsoleApplication1
{
public static class testClass
{
public static string BoolToYesOrNo(this bool text, out string outAsHtmlName)
{
string[] choices = { "Yes", "No", "N/A" };
switch (text)
{
case true: outAsHtmlName = choices[0]; return choices[0];
case false: outAsHtmlName = choices[1]; return choices[1];
default: outAsHtmlName = choices[2]; return choices[2];
}
}
}
class Program
{
static void Main(string[] args)
{
bool b = true;
string result = string.Empty;
string retval = b.BoolToYesOrNo(out result);
Console.WriteLine(retval + ", " + result); //output: "Yes, Yes";
}
}
}
I hit F5 to run the program. The code ran perfectly. So, your method is in fact correct, and there is something wrong ... well, somewhere else. Double check the braces, sometimes if you miss one you get odd errors.
I simply paste your code and it works fine. I tried both .net 3.5 and 4.0 and no compile error is shown and the results are correct.
Why this is an overload method?
Found the answer on a MS forum, was a vs 2012 bug, and after installing the july 2012 update, everything worked fine. Thank you.