The last but 3rd line of code is not recognizing variables that I have declared and filled with strings.
static void Main(string[] args)
{
string inputNumber = "1979";
string input1 = inputNumber.Substring(0, 1);
string input2 = inputNumber.Substring(1, 1);
string input3 = inputNumber.Substring(2, 1);
string input4 = inputNumber.Substring(3, 1);
int intInput1;
int intInput2;
int intInput3;
int intInput4;
intInput1 = Convert.ToInt32(input1);
intInput2 = Convert.ToInt32(input2);
intInput3 = Convert.ToInt32(input3);
intInput4 = Convert.ToInt32(input4);
string stringOutput1;
string stringOutput2;
string stringOutput3;
string stringOutput4;
// 1000 Input.
switch (intInput1)
{
case 1:
stringOutput1 = "M";
break;
default:
break;
}
//100 Input
switch (intInput2)
{
case 9:
stringOutput2 = "CM";
break;
default:
break;
}
//10 Input
switch (intInput3)
{
case 7:
stringOutput3 = "LXX";
break;
default:
break;
}
//1 Input
switch (intInput4)
{
case 9:
stringOutput4 = "IX";
break;
default:
break;
}
//Use of unassigned local variable error is showing for 'stringOutput1', 'stringOutput2', 'stringOutput3' and 'stringOutput4'
Console.WriteLine("{0} is {1}{2}{3}{4} in Roman Numerals",inputNumber, stringOutput1, stringOutput2, stringOutput3, stringOutput4);
Console.CursorVisible = false;
Console.ReadKey();
}
P.S. I know that the variables are being filled by commenting out
Console.WriteLine("{0} is {1}{2}{3}{4} in Roman Numerals",inputNumber, stringOutput1, stringOutput2, stringOutput3, stringOutput4);
and using break point and stepping over the code.
This is because your variables might not have been assigned anything yet. Variables must be guaranteed to have been assigned something before they can be used. As a simple fix, you can use declarations like this:
string stringOutput1 = "";
Try assigning nulls to the declarations
string stringOutput1 = null;
string stringOutput2 = null;
string stringOutput3 = null;
string stringOutput4 = null;
You have to initialize your variables, do it like this.
string stringOutput1 , stringOutput1, stringOutput3, stringOutput4 = string.Empty;
and you can also assign default values per variable.
string stringOutput1 = "foo1", stringOutput1 = "foo2"
, stringOutput3= "foo3", stringOutput4 = "foo4";
Related
Hit everyone! I'm still learning C# and I would like to print different string for each loop based on the switch cases.
static Random rand = new Random();
static void Main(string[] args){
string someString = "";
int someRandom = rand.Next(4);
switch(someRandom) {
case 0:
someString = "Woa";
break;
case 1:
someString = "Waa";
break;
case 2:
someString = "Wee";
break;
case 3:
someString = "Wow!";
break;
}
int someCount = 5;
for (int someInt = 0; someInt < someCount; someInt++) {
Console.WriteLine(someString);
}
Console.Read();
}
What it should do: display random string each loop from the switch.
What it actually does: Selects case randomly and prints the same case in each loop.
I couldn't produce a random string, why is that? I tried adding someRandom = rand.Next(4) inside the for loop but still produces same.
I already tried searching but couldn't find an answer that could solve my problem.
It seems that you are only setting somestring once, and then printing it a bunch. You should put the switch statement in the for loop.
You need to generate the random number (and set the someString variable) inside the loop, otherwise you only pick one random number and then display it multiple times in the loop.
Here's an example but with some slightly better names (IMO):
static Random rand = new Random();
static void Main()
{
int count = 5;
for (int i = 0; i < count; i++)
{
string output;
switch(rand.Next(4))
{
case 0:
output = "Woa";
break;
case 1:
output = "Waa";
break;
case 2:
output = "Wee";
break;
case 3:
output = "Wow!";
break;
default:
output = "This shouldn't happen";
break;
}
Console.WriteLine(output);
}
Console.Read();
}
Sorry for posting this wall of garbage code :( I didn't want to leave anything out! Im still new and got a little ahead of myself. I wanted to put the "switch case" in a new class so I could reference it faster while also learning to make a new class file. Unfortunately I ran into one bug after another and I couldn't figure out why. The main issue i had is that when I call the case number in the main method, it only returns the string.
Ex. I want the output to be:
"Well [user created name], are you ready to begin your journey to the edge of the world?"
It seems there is an issue with the two classes communicating with eachother.
I have made it worse throwing "public static" at everything to try to make it work. I would really appreciate the help.
using System;
using Test;
public class Scripts
{
public Program p { get; set; }
public void Script(int s)
{
switch (s)
{
case 1:
p.output = "Quest to the edge of the world!";
p.WriteLine();
break;
case 2:
p.output = "Hello! I am your instructor. What is your name apprentice?";
p.WriteLine();
break;
case :
p.output = p.name + " you say? My, what a strange name.";
p.WriteLine();
break;
case 4:
p.output = "Well " + p.name + ", are you ready to begin your journey to the edge of the world?";
p.WriteLine();
break;
case 5:
p.output = " (y)Yes on (n)No";
p.WriteLine();
break;
case 6:
p.output = "OK! Before we go lets go over our gear. What should we prioritize? (1)Magic, (2)Melee, or (3)Ranged?";
p.WriteLine();
break;
case 7:
p.output = "Well I'll just come back tomorrow then.";
p.WriteLine();
break;
case 8:
p.output = "I'm sorry... that's not an option.";
p.WriteLine();
break;
case 9:
p.output = "I'm pretty good at " + p.combatStyle + " combat myself, I'll be sure to teach you everything I know.";
p.WriteLine();
break;
case 10:
p.output = "OK! Let's hit the road and make camp at sundown.";
p.WriteLine();
break;
case 11:
p.output = "Chapter " + p.chapter;
p.WriteLine();
break;
case 12:
p.output = p.name + ", wake up!Were under attack by a couple of goblins!";
p.WriteLine();
break;
case 13:
p.output = "I guess this is the perfect chance to teach you a new" + p.form + "called";
p.WriteLine();
break;
case 14:
p.output = "It makes quick work of their health, but your" + p.energyBar + " will go down just as fast so use it wisely!";
p.WriteLine();
break;
case 15:
p.output = "I'll take care of the one on the right, you engage the one on the left.";
p.WriteLine();
break;
case 16:
p.output = "Press (f) to enter combat. Then press (1) to make an attack";
p.WriteLine();
break;
default:
break;
}
}
}
using System;
using System.Threading;
namespace Test
{
public class Program
{
public Scripts s { get; set; }
// Class Global Variables
public static string input;
public static string output;
public static string name = "bob";
private static string yes = "y";
private static string no = "n";
private static string option1 = "1";
private static string option2 = "2";
private static string option3 = "3";
private static string pathA;
private static string pathB;
private static string pathC;
public static string combatStyle;
private static string weapon;
public static string chapter = "Zero";
public static string form;
public static string energyBar;
private static string healthBar;
Program p = new Program();
public static string[] numbers = new string[] { "One","Two", "Three", "Four", "Five" };
private static int mp = 100;
private static int stamina = 100;
private static int script;
//ReadLine & WriteLine Methods
private static void ReadLine()
{
Console.SetCursorPosition((Console.WindowWidth - 110) / 2, Console.CursorTop);
input = Console.ReadLine();
}
public static void WriteLine()
{
Thread.Sleep(2000);
Console.SetCursorPosition((Console.WindowWidth - output.Length) / 2, Console.CursorTop);
Console.WriteLine(output);
}
//Next Chapter Screen
private static void nextChapter()
{
Thread.Sleep(3000);
Console.Clear();
Thread.Sleep(1500);
output = "\r\n\r\n\r\n\r\n";
WriteLine();
//output = script[12] + chapter;
WriteLine();
Console.Beep();
Thread.Sleep(1500);
Console.Clear();
}
//Yes or No Decision
private static void YesNo()
{
while (input != yes && input != no)
{
ReadLine();
if (input == yes)
{
output = pathA;
WriteLine();
}
else if (input == no)
{
output = pathB;
WriteLine();
}
else
{
//output = script[8];
WriteLine();
}
}
input = "";
}
//Multiple Choice Decision
private static void Choice()
{
while (input != option1 && input != option2 && input != option3)
{
ReadLine();
if (input == option1)
{
output = pathA;
WriteLine();
}
else if (input == option2)
{
output = pathB;
WriteLine();
}
else if (input == option3)
{
output = pathC;
WriteLine();
}
else
{
//output = //script[8];
//WriteLine();
}
}
input = "";
}
//Combat Loop
private static void combatLoop()
{
if (input == "f")
{
}
else
{
//output = script[8];
WriteLine();
combatLoop();
}
}
//Main Method
static void Main()
{
//Chapter Zero "Intro"
Scripts s = new Scripts();
s.Script(1);
s.Script(2);
ReadLine();
name = input;
Console.WriteLine(input);
Console.WriteLine(name);
s.Script(3);
//Chapter One "Combat"
//Chapter Two "Trading"
//Chapter Three "Dungeon"
//Chapter Four "Sailing"
//Chapter Five "The Edge"
// Keep the console open in debug mode.
Console.WriteLine("Press any key to quit game.");
Console.ReadKey();
}
}
}
Looks like your class is in a separate namespace, and the existing namespace for program is not using a using statement for including your separate class.
If you're using static methods / variables, you shouldn't use the object, you should use the class itself:
Program.output = "bla";
Program.WriteLine();
instead of
p.output = "bla";
p.WriteLine();
As your field p isn't even initalized, your current code shouldn't compile. If you want to use the object, you should pass it like that:
public void Script (int s, Program p)
Then you could also make your methods non-static.
Also I'm wondering why you're setting your cursor position to half the length of the text from the right - why not the full offset?
Furthermore you're saying that
The main issue i had is that when I call the case number in the main method, it only returns the string.
What do you mean by returning the string? Your Script method doesn't even have a return type (except for void).
string returnString;
switch(Type) {
case 0: returnString = exampleFunction(foo0, out int exitCode); break;
case 1: returnString = exampleFunction(foo1, out int exitCode); break;
case 2: returnString = exampleFunction(foo2, out int exitCode); break;
}
When I write this code, VS displayed me an error that 'A local variable named or function named 'exitCode' is already defined in this scope' for line 4 and 5. So if I want to get more than two variables with different types from exampleFunction, what should I do? If I can't use out in the code, should I use tuple to get returnString and exitCode from the function?
You could declare exitCode variable before the switch. You should initialize it with some value or have default branch in you switch. Otherwise there is a flow by which exitCode will be uninitialized after the switch. Compiler will not pass this. Also don't forget a break after each case:
int exitCode = 0;
string returnString;
switch(Type) {
case 0: returnString = exampleFunction(foo0, out exitCode); break;
case 1: returnString = exampleFunction(foo1, out exitCode); break;
case 2: returnString = exampleFunction(foo2, out exitCode); break;
}
But overall having a method returning two different values (one as return value and second as out parameter) is a bad practice. Consider having some simple class with those values as properties:
class SomeValue
{
public string Foo { get; set; }
public int Code { get; set; }
}
static SomeValue ExampleFunction(string input)
{
return new SomeValue
{
Foo = input,
Code = 1,
};
}
static void Main(string[] args)
{
// ...
SomeValue val = null;
switch (Type)
{
case 0: val = ExampleFunction(foo0); break;
case 1: val = ExampleFunction(foo1); break;
case 2: val = ExampleFunction(foo2); break;
}
}
Instead of declaring foo0, foo1, and foo2, perhaps you should consider using an array, e.g. foo[]. This is usually a good idea whenever you see variable names with ascending numbers like that.
If you do it that way, the problem goes away, and you code is much shorter:
var returnString = exampleFunction(foo[Type], out int exitCode);
If it doesn't make sense within the problem domain for foo0, foo1, and foo2 to live in an array (e.g. their individual names are important), you can still use a temporary array as a map:
var returnString = exampleFunction(
new[] {foo0, foo1, foo2} [Type],
out int exitCode
);
You should declare "exitCode" only for the first time
case 0: returnString = exampleFunction(foo0, out int exitCode); break;
case 1: returnString = exampleFunction(foo1, out exitCode); break;
case 2: returnString = exampleFunction(foo2, out exitCode); break;
Once you declare it "inline", it becomes local variable for that block.
I have a string being passed to me which can be between 1 and 6 characters long. Depending on the length of the string I need to add the appropriate prefix to the start of the string and return the appeneded string. So if I have something like the following passed to me
1
12
123
1234
12345
123456
I want the return string to look like
X000001
X000012
X000123
X001234
X012345
X123456
I have come up with the following method
public static string AddToStartOfString(string s)
{
string value = string.Empty;
switch (s.Length)
{
case 1:
value = "X00000" + s;
break;
case 2:
value = "X0000" + s;
break;
case 3:
value = "X000" + s;
break;
case 4:
value = "X00" + s;
break;
case 5:
value = "X0" + s;
break;
case 6:
value = "X" + s;
break;
}
return value;
}
This works. But I need this to work in case in future more lengths are added. Is there a way where I can add the prefix even if the length of string is greater than 6 in the future
You can do this:
public static string AddToStartOfString(string s, int digitCount = 6)
{
return "X" + s.PadLeft(digitCount, '0');
}
Beware that an input string longer than the max number of digits, once transformed, will not be truncated and will be longer than for values in the correct range.
had a similar problem recently, in your case i would do:
public static string Fill(string str, string prefix, int length)
{
for(int i=str.Length; i<length; i++)
str = "0" + str;
return prefix + str;
}
I'm seeing some strange behavior when using a nullable long switch statement in VS2015 Update 1 that I'm not seeing in other Visual Studio releases where it runs as expected.
class Program
{
static void Main(string[] args)
{
NullableTest(-1);
NullableTest(0);
NullableTest(1);
NullableTest(2);
NullableTest(null);
}
public static void NullableTest(long? input)
{
string switch1;
switch (input)
{
case 0:
switch1 = "0";
break;
case 1:
switch1 = "1";
break;
default:
switch1 = "d";
break;
}
string switch2;
switch (input)
{
case -1:
switch2 = "-1";
break;
case 0:
switch2 = "0";
break;
case 1:
switch2 = "1";
break;
default:
switch2 = "d";
break;
}
string ifElse;
if (input == 0)
{
ifElse = "0";
}
else if (input == 1)
{
ifElse = "1";
}
else
{
ifElse = "d";
}
Console.WriteLine("Input = {0}, Switch 1 output = {1}, Switch 2 output = {2}, If Else = {3}", input, switch1, switch2, ifElse);
}
This sample code produces the following output (Aligned for readability):
Input = -1, Switch 1 output = d, Switch 2 output = d, If Else = d
Input = 0, Switch 1 output = 0, Switch 2 output = d, If Else = 0
Input = 1, Switch 1 output = d, Switch 2 output = d, If Else = 1
Input = 2, Switch 1 output = d, Switch 2 output = d, If Else = d
Input = , Switch 1 output = d, Switch 2 output = d, If Else = d
I'm only observing this behavior with Nullable types. Non-nullable types work as expected.
Note that this is not the same behavior that's in this question, and is not caused by this compiler bug that's been fixed in VS2015 Update 1. I've verified that both of those examples run correctly.
It looks like this is caused by this bug, and was fixed with this pull request.
I've tried a recent build of Roslyn and the sample code in the question works as expected now.
Here is the updated version of MSBuild Tools 2015 that has corrected the issue.
This is a bug. I believe it must be a left over of the same bug. You better replace your code with an If to avoid any unexpected behavior.