I tried to make a piece of code which would roll a dice in the end to decide which character wins and it keeps on saying that there are errors (Use of unassigned local variable 'skillmodifier') & (Use of unassigned local variable 'strengthmodifier'). I would really appreciate any help. P.S I have only been doing programming for a short period of time on Visual Studio 2010. Please help me find a solution to this problem, the problem occurs because I use the variables 'strengthmodifier' and 'skillmodifier' twice. Thank you, yours faithfully, Vikash.
I will paste the task breif below and the code after that:
Task 3 Determining the outcome of an encounter
When there is an encounter between two characters the outcome is determined by the following
process:
• The differences between the strength attributes for the two characters is calculated
• This difference is divided by 5 and then rounded down to create a ‘strength modifier’
• The process is repeated for the skill attribute to create a ‘skill modifier’
• Each player throws a 6 sided dice.
• If the scores on both dice are the same, no changes are made
• If the scores are not the same, the player with the highest score adds the ‘strength
modifier’ to the strength value and the ‘skill modifier’ to the skill value for their
character
• The player with the lower score on the dice subtracts these modifiers from the
strength and skill values for their character
• If a skill value becomes negative, then it is stored as zero
• If a strength value becomes zero or negative, then the character dies.
The program should:
*• Allow the user to input the strength and skill for two characters.
• Display the outcome of the encounter using the process above.
Design an algorithm to describe this process. Write, test and evaluate the code.*
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Task3
{
class Program
{
static void loopfsto()
{
Console.WriteLine("Please enter a value of strength, and then press enter");
string csto = Console.ReadLine(); // Read string from console
int csto1;
if (int.TryParse(csto, out csto1)) // Try to parse the string as an integer
{
Console.WriteLine("Your chosen number is " + csto1 + ".");
Console.ReadKey();
}
else
{
Console.Clear();
Console.WriteLine("Not an integer!");
Console.ReadKey();
Console.Clear();
loopfsto();
}
}
static void loopfsko()
{
Console.WriteLine("Please enter a value of skill, and then press enter");
string csko = Console.ReadLine(); // Read string from console
int csko1;
if (int.TryParse(csko, out csko1)) // Try to parse the string as an integer
{
Console.WriteLine("Your chosen number is " + csko1 + ".");
Console.ReadKey();
}
else
{
Console.Clear();
Console.WriteLine("Not an integer!");
Console.ReadKey();
Console.Clear();
loopfsko();
}
Console.Clear();
}
static void loopfstt()
{
Console.WriteLine("Please enter a value of strength for, and then press enter");
string cstt = Console.ReadLine(); // Read string from console
int cstt1;
if (int.TryParse(cstt, out cstt1)) // Try to parse the string as an integer
{
Console.WriteLine("Your chosen number is " + cstt1 + ".");
Console.ReadKey();
}
else
{
Console.Clear();
Console.WriteLine("Not an integer!");
Console.ReadKey();
Console.Clear();
loopfstt();
}
Console.Clear();
}
static void loopfskt()
{
Console.WriteLine("Please enter a value of skill for, and then press enter");
string cskt = Console.ReadLine(); // Read string from console
int cskt1;
if (int.TryParse(cskt, out cskt1)) // Try to parse the string as an integer
{
Console.WriteLine("Your chosen number is " + cskt1 + ".");
Console.ReadKey();
}
else
{
Console.Clear();
Console.WriteLine("Not an integer!");
Console.ReadKey();
Console.Clear();
loopfskt();
}
}
static void Main(string[] args)
{
string Character1;
string Character2;
int strengthmodifiertoround;
int skillmodifiertoround;
int strengthmodifier;
int skillmodifier;
Console.Title = "Strength and Skill";
Console.WriteLine("Welcome to Strength and Skill, please press enter to continue.");
Console.ReadKey();
Console.Clear();
Console.WriteLine("Please enter a name for character 1, then press enter.");
Character1 = Console.ReadLine();
Console.Clear();
Console.WriteLine("Please enter a name for character 2, then press enter.");
Character2 = Console.ReadLine();
Console.Clear();
Console.WriteLine("Please enter a value of strength for " + Character1 + ", and then press enter");
string csto = Console.ReadLine(); // Read string from console
int csto1;
if (int.TryParse(csto, out csto1)) // Try to parse the string as an integer
{
Console.WriteLine("Your chosen number is " + csto1 + ".");
Console.ReadKey();
}
else
{
Console.Clear();
Console.WriteLine("Not an integer!");
Console.ReadKey();
Console.Clear();
loopfsto();
}
Console.Clear();
Console.WriteLine("Please enter a value of skill for " + Character1 + ", and then press enter");
string csko = Console.ReadLine(); // Read string from console
int csko1;
if (int.TryParse(csko, out csko1)) // Try to parse the string as an integer
{
Console.WriteLine("Your chosen number is " + csko1 + ".");
Console.ReadKey();
}
else
{
Console.Clear();
Console.WriteLine("Not an integer!");
Console.ReadKey();
Console.Clear();
loopfsko();
}
Console.Clear();
Console.WriteLine(Character1 + " has a strength of " + csto1 + " and a skill of " + csko1 + ".");
Console.ReadKey();
Console.Clear();
Console.WriteLine("Please enter a value of strength for " + Character2 + ", and then press enter");
string cstt = Console.ReadLine(); // Read string from console
int cstt1;
if (int.TryParse(cstt, out cstt1)) // Try to parse the string as an integer
{
Console.WriteLine("Your chosen number is " + cstt1 + ".");
Console.ReadKey();
}
else
{
Console.Clear();
Console.WriteLine("Not an integer!");
Console.ReadKey();
Console.Clear();
loopfstt();
}
Console.Clear();
Console.WriteLine("Please enter a value of skill for " + Character2 + ", and then press enter");
string cskt = Console.ReadLine(); // Read string from console
int cskt1;
if (int.TryParse(cskt, out cskt1)) // Try to parse the string as an integer
{
Console.WriteLine("Your chosen number is " + cskt1 + ".");
Console.ReadKey();
}
else
{
Console.Clear();
Console.WriteLine("Not an integer!");
Console.ReadKey();
Console.Clear();
loopfskt();
}
Console.Clear();
Console.WriteLine(Character2 + " has a strength of " + cstt1 + " and a skill of " + cskt1 + ".");
Console.ReadKey();
Console.Clear();
//--- Finds out if strength for character 1 is higher than 2 or vice versa. Then finds difference between two and makes a variable called strengthmodifier ---//
{
if (csto1 < cstt1)
{
strengthmodifiertoround = cstt1 - csto1;
strengthmodifier = strengthmodifiertoround / 5;
}
if (cstt1 < csto1)
{
strengthmodifiertoround = csto1 - cstt1;
strengthmodifier = strengthmodifiertoround / 5;
}
}
//--- Finds out if skill for character 1 is higher than 2 or vice versa. Then finds difference between two and makes a variable called skillmodifier ---//
{
if (csko1 < cskt1)
{
skillmodifiertoround = cskt1 - csko1;
skillmodifier = skillmodifiertoround / 5;
}
if (cskt1 < csko1)
{
skillmodifiertoround = csko1 - cskt1;
skillmodifier = skillmodifiertoround / 5;
}
}
//--- Tells user to put input and roll a virtual dice (which is actually creating a number between 1 and 6) ---//
Console.WriteLine(Character1 + ", please press enter to roll dice");
Console.ReadKey();
Random rand = new Random();
int character1RandomNumber = rand.Next(1, 6);
Console.WriteLine(Character2 + ", please press enter to roll dice");
Console.ReadKey();
Random rand1 = new Random();
int character2RandomNumber = rand1.Next(1, 6);
Console.WriteLine(Character1 + " rolled a " + character1RandomNumber + " and " + Character2 + " rolled a " + character2RandomNumber + ".");
Console.ReadKey();
if (character1RandomNumber < character2RandomNumber)
{
int char2st = cstt1 + strengthmodifier;
int char2sk = cskt1 + skillmodifier;
int char1st = csto1 - strengthmodifier;
int char1sk = csko1 - skillmodifier;
}
if (character2RandomNumber < character1RandomNumber)
{
}
int ch2st = cstt1 - strengthmodifier;
int ch2sk = cskt1 - skillmodifier;
int ch1st = csto1 + strengthmodifier;
int ch1sk = csko1 + skillmodifier;
}
}
}
Actually, i think your problem is because skillmodifier and strengthmodifier do not get assigned values on all code paths. ie. They are only assigned values from within if clauses and visual studio cannot determine whether or not they are assigned for all possible outcomes. This warning shouldn't stop your code compiling but if you want it to go away you can do something like
int skillmodifiertoround = 0;
instead of just
int skillmodifiertoround;
Now skillmodifiertoround is given a value on declaration.
Edit: "This warning shouldn't stop your code compiling" - Apparently it will stop the program from compiling correctly in c# but the same error in vb only gives a warning but still compiles.
Its rather simple really
int skillmodifier;
You need to assign it - that is give it a value, even a default one - before you can use it. Otherwise the program doesn't know what value it has.
So something like
int skillmodifier = -1;
will fix it for you.
When you declare int skillmodifier declare it as whatever the default value should be,e.g. int skillmodifier = 0;
Do the same for strengthmodifier and you should be good to go!
The problem is that the compiler can detect a way of executing your code without these parameters being set.
Local variables in C# must be initialized before they are used.
From MSDN
Also see related questio Why aren't unassigned local variables automatically initialized?
For generics where type is not known, use default keyword
I think the other people have given you the answer, but I spotted something else.
Instead of
//method
if(tryparse)
{
//done
}
else
//loop
you should turn the methods into methods that return ints and then...
int csko = loopCsko()
Related
I want to ask the user if they want to continue adding two numbers, so if they type Y it would start again if N it will exit.
I'm not sure if I should use if/else or while (or both!) or something else.
Here is what I have so far:
Console.Write("Enter a number to add: ");
int num1 = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter another number to add: ");
int num2 = Convert.ToInt32(Console.ReadLine());
int num3 = num1 + num2;
string num11 = Convert.ToString(num1);
string num22 = Convert.ToString(num2);
Console.WriteLine(" " + num1 + " + " + num2 + " = " + num3);
Console.Write("Do You want to add more numbers? Y / N");
Console.ReadLine();
How can I finish it?
First, let's extract method ReadInt (why should you repeat yourself?):
private static int ReadInt(string title) {
// keep asking user until correct value provided
while (true) {
if (!string.IsNullOrWhiteSpace(title))
Console.WriteLine(title);
// If we can parse user input as integer...
if (int.TryParse(Console.ReadLine(), out int result))
return result; // .. we return it
Console.WriteLine("Syntax error. Please, try again");
}
}
Main code: Here, you can wrap the code fragment into do {...} while (since you want the loop to be performed at least once)
do {
int num1 = ReadInt("Enter a number to add: ");
int num2 = ReadInt("Enter another number to add: ");
// (long) num1 - we prevent integer overflow (if num1 and num2 are large)
Console.WriteLine($" {num1} + {num2} = {(long)num1 + num2}");
Console.WriteLine("Do You want to add more numbers? Y / N");
}
while(Console.ReadKey().Key == ConsoleKey.Y);
while (true)
{
Console.Write("Enter a number to add: ");
int num1 = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter another number to add: ");
int num2 = Convert.ToInt32(Console.ReadLine());
int num3 = num1 + num2;
string num11 = Convert.ToString(num1);
string num22 = Convert.ToString(num2);
Console.WriteLine(" " + num1 + " + " + num2 + " = " + num3);
Console.WriteLine("Do You want to add more numbers? Y / N");
string YesOrNo = Console.ReadLine();
if (YesOrNo == "N")
{
break;
}
}
You need a loop the most common that I see for a scenario like this is the while loop. You also however need a break condition so that the while loop ends an if statement is one way you could break out like in my example above. The break is reached if the user enters N into the console.
Note my example will continue to run if anything other than N is typed into the console.
Fixed, but now it automatically presses enter when it gets to the Main(); thing and I can't actually input anything in time. Anyone know what's wrong?
using System;
using System.Linq;
namespace Bruh
{
class Program
{
static void Main()
{
int pog = 0;
int pog2 = 0;
Random r = new Random();
Console.WriteLine("Input a whole number");
string poggers = Console.ReadLine();
if (int.TryParse(poggers, out pog))
{
pog = int.Parse(poggers);
}
else
{
Console.WriteLine("ERROR: Not a number. Please input a number and not letters.");
Console.Read();
System.Environment.Exit(1);
}
Console.WriteLine("Input a number higher than the previous");
string poggers2 = Console.ReadLine();
if (int.TryParse(poggers2, out pog2))
{
pog2 = int.Parse(poggers2);
}
else
{
Console.WriteLine("ERROR: Not a number. Please input a number and not letters.");
Console.Read();
System.Environment.Exit(1);
}
int genRand = r.Next(pog, pog2);
Console.WriteLine("This number was randomly generated between " + pog + " and " + pog2 + " and we got: " + genRand);
Console.Read();
Console.WriteLine("Would you like to try again? Y/N");
ConsoleKeyInfo answer = Console.ReadKey();
if (answer.KeyChar == 'y' || answer.KeyChar == 'Y')
{
Console.WriteLine("\n");
Main();
}
else if (answer.KeyChar == 'n' || answer.KeyChar == 'N')
{
System.Environment.Exit(1);
}
else
{
Console.WriteLine("ERROR: Y/N not any other character");
Console.Read();
System.Environment.Exit(1);
}
}
}
}
I've reworked your code into something that is more C#-like :-) - find this below.
Highlights:
You use int.TryParse() correctly, but do the conversion again
inside the true code block, using int.Parse().
No need to call System.Environment.Exit(1); to terminate the program, just let it end.
The call main() is actually a recursive call - where a method (function) calls it self. Usable sometimes, but i often leads to a StackOverflow exception. In this case, you get some strange behaviour...
using System;
namespace Bruh2
{
class Program
{
static void Main()
{
bool tryAgain = true;
while (tryAgain)
{
int pog = 0;
int pog2 = 0;
Random r = new Random();
Console.Write("Input a whole number: ");
string poggers = Console.ReadLine();
while (!int.TryParse(poggers, out pog))
{
Console.WriteLine("ERROR: Not a number. Please input a number and not letters.");
poggers = Console.ReadLine();
}
Console.Write("Input a number higher than the previous: ");
string poggers2 = Console.ReadLine();
while (!int.TryParse(poggers2, out pog2))
{
Console.WriteLine("ERROR: Not a number. Please input a number and not letters.");
poggers2 = Console.ReadLine();
}
int genRand = r.Next(pog, pog2);
Console.WriteLine("This number was randomly generated between " + pog + " and " + pog2 + " and we got: " + genRand);
Console.WriteLine();
Console.WriteLine("Would you like to try again? Y/N");
//ConsoleKeyInfo answer = Console.ReadKey();
string answer = Console.ReadKey().KeyChar.ToString().ToLower();
while (answer!="y" && answer!="n")
{
Console.WriteLine("ERROR: Y/N not any other character");
answer = Console.ReadKey().ToString().ToLower();
}
if (answer == "n")
{
tryAgain = false; // terminate the loop (and thereby the program)
}
}
}
}
}
sorry if this is a repeat question or sounds pretty stupid, but I'm really new to c# and looked throughout the forum and couldn't find anything that I could actually understand.
So I'm trying to write a simple program where the user tries to guess a number between 1 and 25. Everything works except that each run of the loop instead of updating the score from the last run of the loop, like 0+1=1, 1+1=2, 2+1=3, each time it adds 1 to 0. Here is my code. How do I fix this? Thank you!
int score = 0;
int add = 1;
while (add == 1)
{
Console.WriteLine("Guess A Number Between 1 and 25");
string input = Console.ReadLine();
if (input == "18")
{
Console.WriteLine("You Did It!");
Console.WriteLine("Not Bad! Your Score was " + score + add);
break;
}
else
{
Console.WriteLine("Try Again. Score: " + score + add);
}
}
You need to actually add add to score. Try something like this:
int score = 0;
int add = 1;
while (add == 1)
{
Console.WriteLine("Guess A Number Between 1 and 25");
string input = Console.ReadLine();
score += add; // add `add` to `score`. This is the same as `score = score + add;`
if (input == "18")
{
Console.WriteLine("You Did It!");
Console.WriteLine("Not Bad! Your Score was " + score);
break;
}
else
{
Console.WriteLine("Try Again. Score: " + score);
}
}
So I'm stuck again, I created a 'game choices' program that allows users to choose their 'skill' level. I have wrote all the code but the do loop on line 24 is causing issues. It will not loop when I choose a higher skill level than 4 or when I type 'n' in "Is this what you want (y/n)". Here is the code:
class Program
{
static void Main(string[] args)
{
string name;
int one = 1, two = 2, three = 3, four = 4;
int answer;
int tripalarm = 0;
string verification;
Console.WriteLine("What is your name?");
name = Convert.ToString(Console.ReadLine());
Console.WriteLine(name + ", there are 4 skill levels in this game:");
Console.WriteLine("1. Advanced" + Environment.NewLine + "2. Experienced" + Environment.NewLine + "3. Average"
+ Environment.NewLine + "4. Novice");
do
{
answer = 0;
Console.WriteLine("Which skill level do you choose?");
answer = Convert.ToInt32(Console.ReadLine());
if (answer >= 5)
{
Console.WriteLine("Sorry " + name + " you should choose between 1 and 4:");
}
else if (answer <= 4)
{
if (answer == one)
{
Console.WriteLine("Thank you " + name + ", you have choosen level one");
Console.WriteLine("Is this what you want? (y/n)");
verification = Convert.ToString(Console.ReadLine());
if (verification == "y")
{
Console.WriteLine("Good " + name + " you have chosen level one you can now start the game!");
}
else
{
tripalarm++;
}
}
else if (answer == two)
{
Console.WriteLine("Thank you " + name + ", you have choosen level two");
Console.WriteLine("Is this what you want? (y/n)");
verification = Convert.ToString(Console.ReadLine());
if (verification == "y")
{
Console.WriteLine("Good " + name + " you have chosen level two you can now start the game!");
}
else
{
tripalarm++;
}
}
else if (answer == three)
{
Console.WriteLine("Thank you " + name + ", you have choosen level three");
Console.WriteLine("Is this what you want? (y/n)");
verification = Convert.ToString(Console.ReadLine());
if (verification == "y")
{
Console.WriteLine("Good " + name + " you have chosen level three you can now start the game!");
}
else
{
tripalarm++;
}
}
else if (answer == four)
{
Console.WriteLine("Thank you " + name + ", you have choosen level four");
Console.WriteLine("Is this what you want? (y/n)");
verification = Convert.ToString(Console.ReadLine());
if (verification == "y")
{
Console.WriteLine("Good " + name + " you have chosen level four you can now start the game!");
}
else
{
tripalarm++;
}
}
}
} while (tripalarm == 0);
}
}
I have tried almost everything, changing the while value at the bottom does not change anything. It still loops when it is not supposed to.
Much help would be appreciated, thanks.
This simplifies your code a bit and should correct the bug:
static void Main(string[] args)
{
var levelSelected = false;
var answer = 0;
Console.WriteLine("What is your name?");
string name = Console.ReadLine();
Console.WriteLine($"{name}, there are 4 skill levels in this game:");
Console.WriteLine("1. Advanced");
Console.WriteLine("2. Experienced");
Console.WriteLine("3. Average");
Console.WriteLine("4. Novice");
while (!levelSelected)
{
Console.WriteLine("Which skill level do you choose?");
answer = Convert.ToInt32(Console.ReadLine());
switch (answer)
{
case 1:
case 2:
case 3:
case 4:
Console.WriteLine($"Thank you {name}, you have choosen level {answer}");
Console.WriteLine("Is this what you want? (y/n)");
levelSelected = Console.ReadLine() == "y";
break;
default:
Console.WriteLine($"Sorry {name} you should choose between 1 and 4:");
break;
}
}
Console.WriteLine($"Good {name} you have chosen level {answer} you can now start the game!");
var x = Console.ReadLine();
}
Note it still doesn't check that the user enters an integer for the level (if they don't it will cause an error) and anything other that "y" is treated as "n".
This question already has answers here:
How to loop a Console App
(6 answers)
Closed 6 years ago.
I wanted to try how the if conditional works so I created this code almost by myself. I also had problems with random into int.
Here's my code:
using System;
namespace Bigger_Smaller_Equal
{
class Program
{
static void Main(string[] args)
{
int min = 1;
int max = 100;
Random rnd = new Random();
int gen = rnd.Next(min, max);
Console.WriteLine("My Number is : " + gen + "!");
Console.WriteLine("Tell me your number:");
string typ = Console.ReadLine();
int num = int.Parse(typ);
if (num == gen)
{
Console.WriteLine(num + " is Equal to " + gen);
}
else if (num > gen)
{
Console.WriteLine(num + " Is Bigger than " + gen);
}
else if (num < gen)
{
Console.WriteLine(num + " Is Smaller than " + gen);
}
Console.WriteLine("Press Any Key to exit.");
Console.ReadLine();
}
}
}
How to make the console stop, so it will allow me to enter another number?
Basically:
I write a number it tells me if its smaller bigger or equal to number which was randomly generated
After I press enter instead of closing the console the number will be generated again and I can write new number and so on.
Here's an example using goto, although it is not recommended for more complex applications as you could end up creating endless loops. Feel free to try it out
static void Main(string[] args)
{
int min = 1;
int max = 100;
Random rnd = new Random();
again:
int gen = rnd.Next(min, max);
Console.WriteLine("My Number is : " + gen + "!");
Console.WriteLine("Tell me your number:");
string typ = Console.ReadLine();
int num = int.Parse(typ);
if (num == gen)
{
Console.WriteLine(num + " is Equal to " + gen);
}
else if (num > gen)
{
Console.WriteLine(num + " Is Bigger than " + gen);
}
else if (num < gen)
{
Console.WriteLine(num + " Is Smaller than " + gen);
}
repeat:
Console.WriteLine("Play again? (Y/N)");
string ans = Console.ReadLine();
switch (ans.ToUpper())
{
case "Y": goto again; break;
case "N": break; //continue
default: goto repeat; break;
}
}
You can use console.ReadKey() insted of using console.ReadLine().
console.ReadLine() wait for input set of character thats why you console window is apperre there after pressing any key.
You can use "do while" or "while" operator.If you dont want to use while(true) , you can use this diffirent way. I mean that when user enter 0 or -1 this system can stop. while()
bool repeat = true;
do
{
Console.WriteLine("Enter value ");
string typ = Console.ReadLine();
int num = int.Parse(typ);
if (num!=0)
// bla bla bla.
else
repeat = false;
}while (repeat);