How to start over with my code? C# Console [duplicate] - c#

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);

Related

I dont press enter but ReadLine() says I did (accidently made it that you cant answer the old one so repost)

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)
}
}
}
}
}

How to get out of a while-loop in c#

Here I am trying to have the user enter "YES" to continue with the game but i'm stuck in the while-loop. This is also my first post so I don't the correct way to post ie. copy and paste? Also is there a indentation shortcut for Visual Studio? Thanks for helping.
using System;
namespace BIT_142_Major_Assignment_1
{
class Program
{
static void Main(string[] args)
{
int numGames = 0;
String answer = "";
Random rand = new Random();
int Dice1 = rand.Next(1, 7);
int Dice2 = rand.Next(1, 7);
Console.WriteLine("Hey! Welcome to Andy’s Dice Game.");
Console.WriteLine("Let’s start!");
{
while (true)
{
numGames++;
Console.WriteLine("Dice 1: " + Dice1);
Console.WriteLine("Dice 2: " + Dice2);
Console.WriteLine("I got " + Dice1 + " and " + Dice2 + "!");
if ((Dice1 + Dice2) % 2 == 0)
{
Console.WriteLine("Evens are better than odds!");
}
else
{
Console.WriteLine("Odds are still cool!");
Console.WriteLine("Do you want to play again?");
answer = Console.ReadLine();
if (answer == "YES")
{
continue;
}
else
{
Console.WriteLine("The number of times the dice was thrown is: " + numGames);
Console.WriteLine("Nice Game!");
Console.WriteLine("Thank for playing, Come play again soon!");
break;
}
}
}
}
}
}
}

1. How can I get my random number to be different each time it is printed out? 2. Are there any basic things that I can improve upon? [duplicate]

This question already has answers here:
Random number generator only generating one random number
(15 answers)
Closed 4 years ago.
I am very new to programming as a whole and C# is my first language. I have been working on this project for the past few weeks or so that gives the user 3 options of whether they want to use a random number generator, calculator or roll a dice.
So far everything is going okay. I have been focusing quite a lot on exception handling and commenting to make sure that everything is as clear as possible. One problem that I have come across and am not surer how to fix is that in my dice rolling procedure it prints out the same random dice number x times rather than printing out different random numbers each time. So if you could help me fix that that would be awesome. Here is just the code for that;
static void rollDice()
{
Boolean rollAgain = false;
while (rollAgain == false)
{
Console.Write("Enter the number of sides on your dice: "); //Need to do exception handling for this
int totalSides = int.Parse(Console.ReadLine());
Console.WriteLine("How many times would you like to roll the {0} sided dice?", totalSides); //Need to do exception handling for this
int numRolls = int.Parse(Console.ReadLine());
for (int i = 0; i < numRolls; i++)
{
Random rnd = new Random();
int diceNumber = rnd.Next(1, totalSides);
Console.Write("\t" + diceNumber);
}
Console.WriteLine("\nIf you like to roll a dice with a different number of sides enter Y\nTo exit the application enter N");
string doRerun = Console.ReadLine();
if (doRerun == "Y" || doRerun == "y")
{
rollAgain = false;
}
else if (doRerun == "N" || doRerun == "n")
{
rollAgain = true;
}
}
}
Also, as I'm a newbie in general, I think some feedback from more experienced users will benefit me as a whole. Is there any mistakes I've made> Any informal rules I have broken? Please let me know I will be very thankful. Here is all of the code;
static void Main(string[] args)
{
Boolean chooseRun = false;
while (chooseRun == false)
{
Console.WriteLine("To use the calculator enter C\nTo use the random number generator enter R\nTo roll a dice enter D");
string chooseProc = Console.ReadLine();
if (chooseProc == "C" || chooseProc == "c")
{
calculator();
chooseRun = true;
}
else if (chooseProc == "R" || chooseProc == "r")
{
numGenerator();
chooseRun = true;
}
else if (chooseProc == "D" || chooseProc == "d")
{
rollDice();
chooseRun = true;
}
else
{
Console.WriteLine("Sorry that was an invalid input. Please try again");
chooseRun = false;
}
}
Console.Write("Goodbye");
Console.ReadKey();
}
/// <summary>
/// Here I have a simple calculator that can do basic functions such as subtraction and then I give them the option to use it again
/// </summary>
static void calculator()
{
int loop = 1;
while (loop == 1)
{
Console.WriteLine("You chose to use the calculator!\nPress the enter key to start"); //Greet the user and give them the option of when they want to start the calculator based upon when they choose to click the enter key
Console.ReadKey(true);
int num1 = 0; //Declaring variables
int num2 = 0;
string operation = "";
int answer;
Boolean gotnum1 = false;
while (gotnum1 == false)
{
Console.Write("Enter the first number in your equation: "); //Then I give them a message to greet them and give them the option of when to start the calculator
try
{
num1 = int.Parse(Console.ReadLine());
gotnum1 = true;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
Boolean gotnum2 = false;
while (gotnum2 == false)
{
Console.Write("Enter the second number in your equation: "); //Then I give them a message to greet them and give them the option of when to start the calculator
try
{
num2 = int.Parse(Console.ReadLine());
gotnum2 = true;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
Boolean gotOpr = false;
while (gotOpr == false)
{
Console.Write("Ok now enter your operation ( x , / , +, -) ");
operation = Console.ReadLine();
switch (operation)
{
case "x":
answer = num1 * num2;
Console.WriteLine(num1 + " " + operation + " " + num2 + " = " + answer);
gotOpr = true;
break;
case "X":
answer = num1 * num2;
Console.WriteLine(num1 + " " + operation + " " + num2 + " = " + answer);
gotOpr = true;
break;
case "/":
try
{
answer = num1 / num2;
Console.WriteLine(num1 + " " + operation + " " + num2 + " = " + answer);
gotOpr = true;
}
catch (DivideByZeroException e)
{
Console.WriteLine("You cannot divide by zero");
}
break;
case "+":
answer = num1 + num2;
Console.WriteLine(num1 + " " + operation + " " + num2 + " = " + answer);
gotOpr = true;
break;
case "-":
answer = num1 - num2;
Console.WriteLine(num1 + " " + operation + " " + num2 + " = " + answer);
gotOpr = true;
break;
default:
Console.WriteLine("Sorry that is an invalid input");
gotOpr = false;
break;
}
}
Console.WriteLine("Do you want to use the calculator again? Select;\nIf you would please enter /Y/\nIf not please enter /N/");
string rerun = Console.ReadLine();
if (rerun.ToUpper() == "N")
{
loop = 0;
}
}
}
/// <summary>
/// This procedure generates a random number and gives the user the option as to whether they would like to generate another
/// </summary>
static void numGenerator()
{
Console.WriteLine("You chose to use the random number generator");
Boolean moreNum = false;
while (moreNum == false)
{
Random r = new Random();
int n = r.Next();
Console.WriteLine(n);
Console.WriteLine("If you would like another number enter Y, otherwise please enter N");
string rerun = Console.ReadLine();
if (rerun == "Y" || rerun == "y")
{
moreNum = false;
}
else if (rerun == "N" || rerun =="n")
{
moreNum = true;
}
}
}
/// <summary>
/// In this procedure a virtual dice is rolled of a user inputted number of times, this too gives the user the option to roll the dice again after rolling it x times
/// </summary>
static void rollDice()
{
Boolean rollAgain = false;
while (rollAgain == false)
{
Console.Write("Enter the number of sides on your dice: "); //Need to do exception handling for this
int totalSides = int.Parse(Console.ReadLine());
Console.WriteLine("How many times would you like to roll the {0} sided dice?", totalSides); //Need to do exception handling for this
int numRolls = int.Parse(Console.ReadLine());
for (int i = 0; i < numRolls; i++)
{
Random rnd = new Random();
int diceNumber = rnd.Next(1, totalSides);
Console.Write("\t" + diceNumber);
}
Console.WriteLine("\nIf you like to roll a dice with a different number of sides enter Y\nTo exit the application enter N");
string doRerun = Console.ReadLine();
if (doRerun == "Y" || doRerun == "y")
{
rollAgain = false;
}
else if (doRerun == "N" || doRerun == "n")
{
rollAgain = true;
}
}
}
You should create the Random object only once, typically create is in a static field (if you create it many times, it would generate the same values every time)
static Random rnd = new Random();

C# How do I error check the input ensuring only integers between 1-100 are accepted

I'm creating a program for a college assignment and the task is to create a program that basically creates random times table questions. I have done that, but need to error check the input to only accept integer inputs between 1-100. I can not find anything online only for like java or for text box using OOP.
Here is my code:
static void help()
{
Console.WriteLine("This program is to help children learn how to multiply");
Console.WriteLine("The program will create times table questions from 1-10");
Console.WriteLine("The user will be given 10 random questions to complete");
Console.WriteLine("The user will get a score out of 10 at the end");
Console.WriteLine("If the user gets the answer wrong, the correct answer will be displayed");
Console.WriteLine("");
Console.ReadLine();
Console.Clear();
}
static void Main(string[] args)
{
int Random1 = 0;
int Random2 = 0;
int Answer;
int Count = 0;
int Score = 0;
int input = 0;
String choice;
Console.WriteLine("To begin the Maths test please hit any key");
Console.WriteLine("If you need any help, just, type help");
choice = Console.ReadLine();
if (choice == "help")
{
help();
}
while (Count != 10)
{
Random numbers = new Random();
Random1 = numbers.Next(0, 11);
Count = Count + 1;
Random numbers2 = new Random();
Random2 = numbers.Next(0, 11);
Console.WriteLine(Random1 + "x" + Random2 + "=");
input = int.Parse(Console.ReadLine());
Answer = Random1 * Random2;
if (Answer == input)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Correct");
Score = Score + 1;
Console.ResetColor();
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Thats the wrong answer, the correct is " + Answer);
Console.ResetColor();
}
}
if (Score > 5)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Good job you got more than 5 answers correct! With a score of " + Score + " out of 10");
Console.ResetColor();
Console.ReadLine();
}
else if (Score < 5)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("");
Console.WriteLine("Try again you got less than 5 correct! With a score of " + Score + " out of 10");
Console.ResetColor();
Console.ReadLine();
}
}
}
}
Firstly, I suggest you to use TryParse instead of Parse to prevent unexpected errors because of invalid inputs. So, try something like that;
Random numbers = new Random();
Random1 = numbers.Next(0, 11);
Count = Count + 1;
Random numbers2 = new Random();
Random2 = numbers.Next(0, 11);
Console.WriteLine(Random1 + "x" + Random2 + "=");
//Modified
int input = 0;
while (true)
{
if (!int.TryParse(Console.ReadLine(), out input))
{
Console.WriteLine("Invalid Input. Please enter a valid integer.");
}
else
{
if (input >= 1 && input <= 100)
{
break;
}
Console.WriteLine("Invalid Input. Please enter a integer between 1-100.");
}
}
//Modified
I'd simply use a loop that will keep asking for input until it
matches your requirement:
int MinVal = 1; // No magic numbers! You may consider placing them in a config
int MaxVal = 100; // or as static readonly class members (a bit like "const").
int input = -1;
for(;;) // "empty" for-loop = infinite loop. No problem, we break on condition inside.
{
// attempt getting input from user
bool parseOK = int.TryParse(Console.ReadLine(), out input);
// Exit loop if input is valid.
if( parseOK && input >= MinVal && input <= MaxVal ) break;
Console.WriteLine( "Errormessage telling user what you expect" );
}
You may also consider granting only N trys to get the input right.
A few hints:
do not use "magic numbers". Define constants or put numbers into Properties/Settings. Name them self-explanatory and document why you chose the value they happen to have.
The errormessage should tell the user what an expected valid input is (as opposed to what they typed in) not just that their input was invalid.
Whats about this?
input = int.Parse(Console.ReadLine());
if(input > 1 && input < 100){
// valid
}else{
// invalid
}

C# 'Unassigned local variable'?

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()

Categories