First time attempting programing. What am I doing wrong here? - c#

enter image description hereFor my first try, I looked up some YouTube tutorials. One is showing how to create a Magic 8 Ball. I am following the instructions pretty much exactly but it won't work. When written like this it's fine:
namespace Magic8Ball
{
class Program
{
static void Main(string[] args)
{
//Preserve Current Console Text Color
ConsoleColor OldColor = Console.ForegroundColor;
//Change Console Text Color
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Magic 8 Ball. By: Conner Bostock");
Console.ForegroundColor = ConsoleColor.White;
Console.Write("Ask a question?: ");
Console.ForegroundColor = ConsoleColor.DarkGray;
String QuestionString = Console.ReadLine();
//Cleaning Up
Console.ForegroundColor = OldColor;
}
String Void TellPeopleTheName(String Text);
}
}
As you see I am trying to try create a String, not that I need one to do this. I just want to see how it works (So when I need it I don't need to re-type it and can just post this) But starting off it says "TellPeopleTheName must declare a body" I'm confused as this did not happen in the video. Not only that but when I cut and paste the code to join with it. For some reason it all breaks and no longer works:
namespace Magic8Ball
{
class Program
{
static void Main(string[] args)
{
//Preserve Current Console Text Color
ConsoleColor OldColor = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.White;
Console.Write("Ask a question?: ");
Console.ForegroundColor = ConsoleColor.DarkGray;
String QuestionString = Console.ReadLine();
//Cleaning Up
Console.ForegroundColor = OldColor;
}
String Void TellPeopleTheName(String Text);
//Change Console Text Color
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Magic 8 Ball. By: Conner Bostock");
The entire bottom section is underlined in red saying "Invalid Token" and Writeline does not exist in this context". This confuses me more as this did not happen in the video either. What am I doing so wrong?
Thanks for the help and sorry for the nooby comments. I'm 20 and always wanted to learn coding but always been too busy working. Recently broke my back and now have plenty of time sitting doing nothing so I figured I would give it a shot.
This is mine (on top) and his (Bellow) and even after your help (I did go and re-watch and noticed I put String Void and not Static void) These problems still are here and I still don't understand. I apologise. I am really trying to learn and understand. This is a section I could skip and still make the 8-ball but I want to know why it does not work and how to fix it so then I know for when I do need to use this.
NEW FULL CODE:
namespace Magic8Ball
{
class Program
{
static void Main(string[] args)
{
//Preserve Current Console Text Color
ConsoleColor OldColor = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.White;
Console.Write("Ask a question?: ");
Console.ForegroundColor = ConsoleColor.DarkGray;
String QuestionString = Console.ReadLine();
//Cleaning Up
Console.ForegroundColor = OldColor;
}
//This will tell people the name
static void TellPeopleTheName()
//Change Console Text Color
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Magic 8 Ball. By: Conner Bostock");
}

This line is out of place and doesn't actually do anything:
String Void TellPeopleTheName(String Text);
It's void, not Void. Casing matters.
You're giving it two return types, String and void. It either returns something or it doesn't.
That's a method header, but you're missing a method body. As a single line of code it doesn't make sense. Methods need to do something.
For example, a method might look like this:
void TellPeopleTheName(string text)
{
// write code in here to do something
}
Then you would invoke (call) that method somewhere from another method, when you want to perform that operation:
TellPeopleTheName("some text");
Or, in the case of a method which returns a string:
string TellPeopleTheName(string text)
{
// code which does something
return "some string";
}
Invoking it would be the same, but you could store the return value in a variable or otherwise use it in some way:
var someVariable = TellPeopleTheName("some text");
(Note: There are an ongoing variety of issues you may encounter even in trying what's described here. The difference between a static and non-static method come to mind, particularly if you try to call this from main(). Or the variety of ways you may return from a method or use the returned value. And so on. There's much to learn. Good luck!)

String Void TellPeopleTheName(String Text);
should be
void TellPeopleTheName(String Text)
{
}
That would take care of "missing body" error!

void should be in lowercase.
You are missing open/close brackets on the method too.

I notice a couple things you've missed in understanding.
What you've tried to do is write a method to write to the console the name of the program, but the method is not structured correctly.
The general structure of a method is...
AccessModifier static/non-static ReturnType MethodName (ParameterType ParameterName) {
//code to do something
}
An access modifier defines how accessible the method is to other code (as a starting programmer, just keep it as public until you become more advanced).
Putting static or nothing (non-static) is a little confusing for a beginner, if you'll be calling the method from Main (a static method) then it will need to be static, that's sufficient enough for a beginner's understanding for now.
The return type defines what the method should return back when the method is called.
The method name is just how the method is called, should be descriptive and clear what the method does.
A parameter type is the type of object that is being passed as a parameter for the method to use.
A parameter name is just a name, the name should easily explain what the parameter's purpose is for the method.
Following this structure, your method should look like...
public static void TellPeopleTheName(string text)
{
//Change Console Text Color
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Magic 8 Ball. By: Conner Bostock");
}
If you want to make the method more "correct", then it would be...
public static void TellPeopleTheName(string nameOfProgram)
{
//Change Console Text Color
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(nameOfProgram);
}
and you would call the method like this...
TellPeopleTheName("Magic 8 Ball. By: Conner Bostock");

Related

Storing a colour in a variable for future use

I am writing a bit of a dungeon crawler as I learn my way through c#. I am using visual studio and the application is a "Console App (.NET Framework)". My problem is that I have an option in the main menu to change text colour and I am trying to find away to make this change all the other times I change the colour so that it returns to a set default.
I have tried to assign the colour to a variable, lets say, default and then do the Console.ForegroundColor = ConsoleColor.default; I looked online everywhere and can't find a fix.
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("example");
Console.ForgroundColor = Console.Color.White;
// This needs to be default ^^
You can create a property that will of ConsoleColor which will considered as a default color.
Just Assign it when ever you want default color should set to Console.ForegroundColor
Something like,
public class Program
{
public static ConsoleColor DefaultColor { get; set; } = ConsoleColor.Black;
public static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("example");
//You can use DefaultColor whenever you want to assign default color to Foreground
Console.ForegroundColor = DefaultColor;
}
}

text in c# like poke games

I'm wondering if you can make c# text have a slight delay between each letter like old games example pokemon. Video example to show exactly what I mean (look at the textbox) https://www.youtube.com/watch?v=vTyt2e90Nu4
I thought it looked weird when the text just appeared directly. I tried doing
Console.Write("something");
Thread.Sleep(200);
Console.Write("something else");
But it didn't turn out good.
Something like this might get you started.
static void Main(string[] args) {
DelayWrite("It's dangerous to go alone!");
DelayWrite("Take this.");
Console.ReadLine();
}
static void DelayWrite(string text, int charDelay = 50, bool delayNewLine = true) {
foreach (char c in text) {
Console.Write(c);
System.Threading.Thread.Sleep(charDelay);
}
if (delayNewLine) System.Threading.Thread.Sleep(1000);
Console.Write(Environment.NewLine);
}
You can then customize the speed of the printout by adding a second parameter to the DelayWrite() function, such as
DelayWrite("It's dangerous to go alone!", 10); for faster, or
DelayWrite("It's dangerous to go alone!", 1000); for slower speed.

Want to conditionally change Console foreground color based on input

I'm trying to make a KeyDown statement work. So I'm writing:
private void KeyDown(object sender, System.Windows.Forms.KeyEventArgs e);
System.Windows.Forms won't work I read that its a Visual Studio Code thing you have to go to Project.json and add System.Windows.Forms as a dependency. I don't know what to write to add it. I searched the web and searched stock overflow. I can't find anything.
I don't know what to type in to add it.
I could be wrong, but I don't believe you can use the System.Windows.Forms assembly with a .Net Core project. My Visual Studio is acting up so I wasn't able to try using it via the project.json imports feature. Having said that, it wouldn't provide you with what you want anyway.
Since you are wanting to capture the input from the user, via the console, and change the color based on some conditions - you'll have to do that manually yourself.
The following is a complete application example that shows how to do that. Essentially you have to evaluate each character entered into the console and determine if it's a number. If it is a number, you have to move the cursor back 1 position so you can overwrite the value that was just entered. Prior to overwriting the value, you change the consoles foreground color.
using System;
namespace ConsoleApp2
{
public class Program
{
public static void Main(string[] args)
{
// Set up an infinite loop that will allow us to forever type unless 'Q' is pressed.
while(true)
{
ConsoleKeyInfo pressedKey = Console.ReadKey();
// If Q is pressed, we quit the app by ending the loop.
if (pressedKey.Key == ConsoleKey.Q)
{
break;
}
// Handle the pressed key character.
OnKeyDown(pressedKey.KeyChar);
}
}
private static void OnKeyDown(char key)
{
int number;
// Try to parse the key into a number.
// If it fails to parse, then we abort and listen for the next key.
// It will fail if anything other than a number was entered since integers can only store whole numbers.
if (!int.TryParse(key.ToString(), out number))
{
return;
}
// If we get here, then the user entered a number.
// Apply our logic for handling numbers
ChangeColorOfPreviousCharacters(ConsoleColor.Green, key.ToString());
}
private static void ChangeColorOfPreviousCharacters(ConsoleColor color, string originalValue)
{
// Store the original foreground color of the text so we can revert back to it later.
ConsoleColor originalColor = Console.ForegroundColor;
// Move the cursor on the console to the left 1 character so we overwrite the character previously entered
// with a new character that has the updated foreground color applied.
Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
Console.ForegroundColor = color;
// Re-write the original character back out, now with the "Green" color.
Console.Write(originalValue);
// Reset the consoles foreground color back to what ever it was originally. In this case, white.
Console.ForegroundColor = originalColor;
}
}
}
The output to the console will look like this:

C# Restarting a console application

I've created a small application that does a small conversion. At the end of the program I've created a method that allows the user to make another calculation if they press 'r'. All I want it to do is if they press r, take them back to the beginning of Main, else terminate program. I do not want to use goto. This is what I've got so far, and the error I'm getting.
http://puu.sh/juBWP/c7c3f7be61.png
I recommend you use another function instead of Main(). Please refer to the code below:
static void Main(string[] args)
{
doSomething();
}
public static void WouldYouLikeToRestart()
{
Console.WriteLine("Press r to restart");
ConsoleKeyInfo input = Console.ReadKey();
Console.WriteLine();
if (input.KeyChar == 'r')
{
doSomething();
}
}
public static void doSomething()
{
Console.WriteLine("Do Something");
WouldYouLikeToRestart();
}
A while loop would be a good fit, but since you say the program should run and then give the user the option to run again, an even better loop would be a Do While. The difference between while and Do While is that Do While will always run at least once.
string inputStr;
do
{
RunProgram();
Console.WriteLine("Run again?");
inputStr = Console.ReadLine();
} while (inputStr == "y");
TerminateProgram();
In your case, you want to repeat something so of course you should use a while loop. Use a while loop to wrap all your code up like this:
while (true) {
//all your code in the main method.
}
And then you prompt the user to enter 'r' at the end of the loop:
if (Console.ReadLine () != "r") {//this is just an example, you can use whatever method to get the input
break;
}
If the user enters r then the loop continues to do the work. break means to stop executing the stuff in the loop.

How to use a variable to include a few lines of text when called?

i'm not sure i'm asking this correctly, so if i'm making a mistake please please let me know.
I've tried googling and searching stack for a few hours and have not found a result I could understand well enough to impliment (but i did try, honest).
I am trying to make a helper method to insert in to several different places in my code.
This is the method
//Tried several methods (Do, Do While, For, et al) to make an insert code
public Boolean insertFormat()//Method stub
{
Console.Clear(); //Clears out gunk, i hate gunk. I want to know I am looking at
Console.WriteLine(title);//prints program title
}
I thought I could call it like so:
while (true)
{
insertFormat;// This is where i'm trying to repeat the lines - i do this several times so i want to include them somehow (conditions vary)
Console.Clear(); //Clears out gunk, i hate gunk. I want to know I am looking at
Console.WriteLine(title);//prints program title
Console.WriteLine("For Breakfast may we suggest:" + bSelections[selectRandomArrayPosition(0, 4)] + "\n");
Console.WriteLine("Please enter \"N\" for a new selection, or any other key to exit \n");
suggestAgain = Console.ReadLine().ToLower();
if (suggestAgain != "n") break;
}
I've tried for loop, do, do while, etc. Tried to do as a variable but didn't do any correctly so as it worked. Generally I ended up with an error saying
'not all code paths return a value'.
I do the clear and reprint the title about 6 times and don't want to have redundant code in my program as I'm told that is not good practice.
Remove the return type (Boolean) from insertFormat method, since you are not returning anything and compiler gives an error. Change it to void
public void insertFormat()//Method stub
{
Console.Clear(); //Clears out gunk, i hate gunk. I want to know I am looking at
Console.WriteLine(title);//prints program title
}
// Calling code
while (true)
{
insertFormat();// This is where i'm trying to repeat the lines - i do this several times so i want to include them somehow (conditions vary)
// Skip them, insertFormat will execute them
//Console.Clear(); //Clears out gunk, i hate gunk. I want to know I am looking at
//Console.WriteLine(title);//prints program title
Console.WriteLine("For Breakfast may we suggest:" + bSelections[selectRandomArrayPosition(0, 4)] + "\n");
Console.WriteLine("Please enter \"N\" for a new selection, or any other key to exit \n");
suggestAgain = Console.ReadLine().ToLower();
if (suggestAgain != "n") break;
}
You had several errors in your code. Here is working version.
public void insertFormat()
{
Console.Clear();
Console.WriteLine(title);
}
while (suggestAgain != "n")
{
insertFormat();
Console.WriteLine("For Breakfast may we suggest:" + bSelections[selectRandomArrayPosition(0, 4)] + "\n");
Console.WriteLine("Please enter \"N\" for a new selection, or any other key to exit \n");
suggestAgain = Console.ReadLine().ToLower();
}

Categories

Resources