Making a console with a print comand - c#

I am trying to make a program that will print whatever is after "print:" in a console application (I don't know how else to explain it)
If you don't understand I think my code will help you
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LiteConsole
{
class Program
{
static void Main(string[] args)
{
while (true)
{
string input = Console.In.ReadLine();
char[] chars = input.ToCharArray();
if (input.Contains("print"))
{
int Place = 0;
int colenPlace = 0;
foreach (char a in chars)
{
Place++;
if (chars[Place].Equals(":"))
{
colenPlace = Place;
break;
}
}
Console.Write(input.Substring(colenPlace));
}
}
}
}
}
When I run the program and type "print:Hello World" it doesn't print "Hello World" like it should, it just goes to the next line.

At a quick glance I can see two bugs in your application:
First, if a ':' character is never found, the code will generate an IndexOutOfBoundsException. This is because you increment the index before you use it, so you're never comparing the first character of the input and will generate an exception after the last character. Move Place++; to the end of the loop to solve this:
foreach (char a in chars)
{
if (chars[Place].Equals(":"))
{
colenPlace = Place;
break;
}
Place++;
}
Second, this will never be true:
chars[Place].Equals(":")
The value is a char, but you're comparing it to a string. Compare it to a char instead:
chars[Place].Equals(':')
Or even just use a direct comparison (which should result in a compile-time error if you try to use a string by mistake):
chars(Place) == ':'

Could probably simplify it to:
static void Main(string[] args)
{
while (true)
{
var input = Console.ReadLine();
if input.StartsWith("print:")
Console.WriteLine(input.Replace("print:", ""));
}
}

Related

Replacing multiple words in a string sentence C#

Hello guys, I don't need the answer but I would look to know and find out what I'm doing wrong. As a beginner I got a very "easy" assignment in my studies. I need to create a string and inside this string I need to replace some words by other words without using the for loop as so: ( also I want to print it but I got no clue where to put Console.WriteLine and google searching for 1 hour didn't work or asking a colleage.
/* Excersice: use with stringbuilder
* cat becomes littlecat
* dog becomes littledog
* mouse becomes littlemouse
* words the must be replace by a
* do not use a loop*/
using System;
using System.Collections.Generic;
using System.Text;
namespace Opgavens_leerpad_3_oefening
{
class Program
{
static string Main(string[] args)
{
StringBuilder sb = new StringBuilder();
string dogCat = new string("Can the cat find the mouse without waking the dog.");
static string replacethisstring(string dogCat);
{
hondKat = dogCat.Replace("cat", "littlecat");
hondKat = dogCat.Replace("dog", "littldog");
hondKat = dogCat.Replace("mouse", "littlemouse");
hondKat = dogCat.Replace("the", "a");
return dogCat;
}
}
}
}
Error CS5001: Program does not contain a static "Main" method suitable for an entry point ( I don't get this doesn't almost any program starts with this static Main args? )
Error CS8112: replacethisstring(string)' is a local function and must therefore always have a body. ( I just gave it a body right? I opened the { and close it } and put a replace with return. )
The method declaration ends with ; that’s the reason for CS8112
The Main method has to return void (or ‘int’ )you’ve modified it to string, that’s the reason for CS5001
If you want the program to print the output on the console use:
using System;
....
Console.WriteLine(output)
Your main should have a void as return type. string is not allowed but int is an option (see reference)
You cannot have ; at the end of a function declaration that has a body to it.
You have to declare a variable before you can use it ... string hondKat;
See the use of StringBuilder in the below code instead of string.
namespace Opgavens_leerpad_3_oefening
{
class Program
{
public static void Main(string[] args)
{
StringBuilder sb = new StringBuilder();
sb.Append("Can the cat find the mouse without waking the dog.");
sb = replacethisstring(sb);
Console.WriteLine(sb.ToString());
Console.ReadLine(); // To Stop the Console from closing.
static StringBuilder replacethisstring(StringBuilder dogCat)
{
dogCat = dogCat.Replace("cat", "littlecat");
dogCat = dogCat.Replace("dog", "littldog");
dogCat = dogCat.Replace("mouse", "littlemouse");
dogCat = dogCat.Replace("the", "a");
return dogCat;
}
}
}
}
You can place the function within the Main or outside. Normally you would find functions outside of the Main class.
public static void Main(string[] args)
{
...
}
public static string replacethisstring(string dogCat)
{
...
}
Having several issues like typos, syntax error etc.
Additionally, the excercise having a condition that needs to use with stringbuilder.
So, try this.
static void Main(string[] args)
{
StringBuilder sb = new StringBuilder("Can the cat find the mouse without waking the dog?");
sb = replacethisstring(sb);
Console.WriteLine(sb.ToString());
Console.ReadLine();
}
static StringBuilder replacethisstring(StringBuilder dogCat)
{
StringBuilder hondKat = dogCat.Replace("cat", "littlecat");
hondKat = dogCat.Replace("the", "a");
hondKat = dogCat.Replace("dog", "littledog");
hondKat = dogCat.Replace("mouse", "littlemouse");
return hondKat;
}

c# - While loop coding theory, making a login and register sysem

I have coded a system based of the theory that while loops can work anywhere in a system. So once a while loop has been passed by it can run. Here is a simple version of my code:
using System;
namespace test___login
{
class Program
{
static void Main(string[] args)
{
string location = "homepage";
while (location.Equals("Homepage", StringComparison.InvariantCultureIgnoreCase))
{
Console.WriteLine("homepage");
Console.WriteLine("WHere to now: ");
location = Console.ReadLine();
}
while (location.Equals("login", StringComparison.InvariantCultureIgnoreCase))
{
Console.WriteLine("login");
Console.WriteLine("Where to now: ");
location = Console.ReadLine();
}
}
}
}
So I assumed that once the variable changes from "login" to "homepage" in the second while loop, would mean the first while loop would run once again. Is my theory on how the code works wrong or am i simply not typing the right thing. I just started last week so sorry for the basic question
It wouldn't run again, because the code has already executed past that line so unless you call it again, the next thing down the line will execute, in your case nothing - this is called procedural programming.
Why don't you make one while loop, and a switch statement instead.
bool run = true;
while (run)
{
Console.WriteLine("WHere to now: ");
string location = Console.ReadLine();
switch(location.ToLower()){
case "homepage":
Console.WriteLine("HomePage");
break;
default:
run = false;
break;
}
}
Not with the way you have your code currently structured. It will exit the application. You need to surround all of that with one more while loop, which can be similar to your other loops. See below:
using System;
namespace test___login {
class Program
{
static void Main(string[] args)
{
string location = "homepage";
while (!location.ToUpper().Equals("EXIT"))
{
while (location.Equals("Homepage", StringComparison.InvariantCultureIgnoreCase))
{
Console.WriteLine("homepage");
Console.WriteLine("WHere to now: ");
location = Console.ReadLine();
}
while (location.Equals("login", StringComparison.InvariantCultureIgnoreCase))
{
Console.WriteLine("login");
Console.WriteLine("Where to now: ");
location = Console.ReadLine();
}
}
}
}
}

While (true) problems, what did i do wrong?

Why when I type "gamble" the first time, only the if statement works? It's no use typing anything else, it still adds 10 woods. And why when I type anything else the first time, just the else statement works? It is no use typing "gamble, will continue saying " Write '' gamble '' to hit the tree. " PS: The variable its int = woods; and string gamble;
Console.WriteLine("You have {0} woods", woods);
Console.WriteLine("Write ''gamble'' to hit the tree");
gamble = Console.ReadLine();
bool loop = true;
while (loop)
{
if (gamble.Contains("gamble"))
{
woods = woods + 10;
Console.Clear();
}
else
{
Console.WriteLine("Write ''gamble'' to hit the tree");
}
Console.WriteLine("You have {0} woods", woods);
Console.ReadLine();
}
gamble = Console.ReadLine();
You only set gamble in the beginning. In the loop it is never changed. So it keeps using the first value over and over again.
Add gamble = to the last line of the loop.
If I understand what your are describing, you forgot to read into gamble again
Console.WriteLine("You have {0} woods", woods);
gamble = Console.ReadLine();
}
At the end of the while loop, you are doing Console.ReadLine() but not storing it. You need gamble = Console.ReadLine() to store the scanned string in the "gamble" variable.
Because loop is always true. You should change it to false after if and else statements...
The reason it's adding 10 wood regardless if there is something else than "gamble" in the console line, is because you're writing "gamble" in the returning message.
else {Console.WriteLine("Write ''gamble'' to hit the tree");} is the problem here.
You can fix it by either not writing the word "gamble" inside the returning message, or find a clever way to not have it run in a while(true) loop.
You can, for example, use the main method to have it run the function you're going to run just once.
Something like this.
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace ConsoleApp1
{
class Program
{
// Set a `wood` variable for the class.
protected int wood { get; set; }
static void Main(string[] args)
{
Program program = new Program(); // Making use of non-static methods.
program.Handler();
}
public void Handler()
{
Console.WriteLine("Write \"gamble\" to hit the tree.");
string message = Console.ReadLine();
if (message == "gamble")
{
addWood(); // Call the non-static method.
}
}
public bool addWood()
{
this.wood = this.wood + 10;
Console.WriteLine("You now have {0} wood!", this.wood);
Handler(); // Call the Handler() method again for infinite loop.
return true;
}
}
}
WARNING: The program will exit if there is something else than "gamble" written.

how to recall variable in foreach Loop C#

I'm new to C#. I wrote a foreach loop,but how can I recall the variables outside the loop. Thanks for your help.
Here is my code:
static void Main(string[] args)
{
IDictionary<string,float> IDico=new Dictionary<string,float>();
IDico.Add("D1",1);
IDico.Add("D2",2);
IDico.Add("D3",3);
string tempo="D2";
foreach(var element in IDico.Keys)
{
if(tempo.Contains(element in IDico.Keys)
{
var outPut=IDico[element]
}
}
var call=outPut // How can I call outPut outside the for loop?Because the outPut doesn't exist for this row.
}
This is your code
static void Main(string[] args)
{
IDictionary<string,float> IDico=new Dictionary<string,float>();
IDico.Add("D1",1);
IDico.Add("D2",2);
IDico.Add("D3",3);
string tempo="D2";
float outPut = 0.0;
foreach(var element in IDico.Keys)
{
if(tempo.Contains(element))
{
outPut=IDico[element]
}
}
//Do stuff with outPut
}
however i think you may be trying to find tempo in the dictionary so really you should just do this:
static void Main(string[] args)
{
IDictionary<string,float> IDico=new Dictionary<string,float>();
IDico.Add("D1",1);
IDico.Add("D2",2);
IDico.Add("D3",3);
string tempo="D2";
float outPut = 0.0;
if(IDico.Contains(tempo))
{
outPut=IDico[tempo];
}
//Do stuff with outPut
}
static void Main(string[] args)
{
IDictionary<string,float> IDico=new Dictionary<string,float>();
IDico.Add("D1",1);
IDico.Add("D2",2);
IDico.Add("D3",3);
string tempo="D2";
string outPut = string.Empty;
foreach(var element in IDico.Keys)
{
if(tempo.Contains(element))
{
outPut = IDico[element]
}
}
var call = outPut;
}
If outPut can contain more than one element from your dictionary consider using and array or list. If you want to stop iterating after you find a match use a break; in the if statement so that after the match is found the loop will stop.
Also, you're going to want to declare outPut outside of loop so it doesn't re declare itself on each iteration of the loop.
I also fixed the contains statement for you as well as you were using improper syntax.

C# - Using Settings

I've recently written this short application in C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Checker
{
class Program
{
static void Main(string[] args)
{
Properties.Settings.Default.Save();
Program re = new Program();
re.next();
}
public void next()
{
Console.WriteLine("Have you already entered name?");
int ch = int.Parse(Console.ReadLine());
if (ch == 0)
{
Console.WriteLine("What is your name?");
String name = Console.ReadLine();
Console.WriteLine("Thank you!");
Console.ReadKey();
}
Console.WriteLine("Your name is " + name);
}
}
}
Now, I've created a settings file, and created a "name" variable there, with the "String" type.
The scope of it is "User".
So I want it to load the "name" variable with the properties line, but I can't even compile the program because of this error:
Error 1 The name 'name' does not exist in the current context
How can I solve it?
The answer to your problem becomes a little more apparent when you indent:
String name;
if (ch == 0)
{
Console.WriteLine("What is your name?");
name = Console.ReadLine();
Console.WriteLine("Thank you!");
Console.ReadKey();
}
else
{
name = Settings.Default.name;
}
Console.WriteLine("Your name is " + name);
Now you can see that you defined a String called name inside the if-block, thus using it in the Console.WriteLine outside the if-block is out of scope! Move that last Console.WriteLine inside the if-block to solve the scoping issue.
Edit: Based on your comment, your code needs a bit more logic to attain what you're trying to do. I updated my snippet above to accomplish what I think you're trying to do.
You declared that variable inside the if block.
As the compiler is trying to tell you, it doesn't exist outside that block.
If you want to use your Settings class, write Settings.Default.Name.
Your intentions are a bit unclear, but to me it seems as though you are trying to have the application display the name of the user if it has already been saved or ask for it if it hasn't. If that is the case, something like this should work:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Checker
{
class Program
{
static void Main(string[] args)
{
Program re = new Program();
re.next();
Properties.Settings.Default.Save();
}
public void next()
{
String name = Settings.Default.name;
if (String.IsNullOrEmpty(name))
{
Console.WriteLine("What is your name?");
name = Console.ReadLine();
Settings.Default.name = name;
Console.WriteLine("Thank you!");
Console.ReadKey();
}
else
{
Console.WriteLine("Your name is " + name);
}
}
}
}
In your OP, your settings were not being saved before the program exited nor were you setting the name property.

Categories