How do I repeat this code/game if the player gets the answer wrong?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Random RandomGenerator = new Random();// random number generator
Console.WriteLine("i have thought of a number between 1 and 100");//display message
//
//
int IN_RandomNum = RandomGenerator.Next(1, 100); //the range
//loop 10 times
for (int i = 0; i < 10; i++) //for loop created
{
int IN_Guess; //guessing integer
Console.Write("{0} turns left, enter your next guess>", 10 - i);//number of turns players has
//
IN_Guess = Convert.ToInt32(Console.ReadLine()); //string to number
//Now check if guess is same as generated
if (IN_Guess == IN_RandomNum)//if guess is equal to generated number
{
Console.WriteLine("correct in {0} turns", i + 1); //if guessed correctly
break; //breaking code
}
else if (IN_Guess > IN_RandomNum) //if guess is higher than generated number
{
Console.WriteLine("Too high");// if guessed number is too high
}
else //then...
{
Console.WriteLine("Too low"); // if guessed number is too low
} if (i==8) //on last turn display this message
{
Console.WriteLine("*YOU ONLY HAVE 1 GUESS LEFT!*"); //display this message
}
}
Console.WriteLine("please press enter to quit"); //display message
Console.ReadLine();//keeps application open until enter button hit
}
}
}
Please help because i really cant figure out where to put the while loop...ive ran out of ideas
You would need to wrap everything in a while loop.
When it exits the for loop you have, it doesn't matter if they win or lose you go back to the top and start again, generating a new random number.
Before reading the code below, see my suggestion above and attempt it yourself, see if you can crack it
Something like this:
static void Main(string[] args)
{
Random RandomGenerator = new Random();// random number generator
while (true)
{
Console.WriteLine("i have thought of a number between 1 and 100");//display message
bool guessedCorrect = false;
int IN_RandomNum = RandomGenerator.Next(1, 100); //the range
//loop 10 times
for (int i = 0; i < 10; i++) //for loop created
{
int IN_Guess; //guessing integer
Console.Write("{0} turns left, enter your next guess>", 10 - i);//number of turns players has
//
IN_Guess = Convert.ToInt32(Console.ReadLine()); //string to number
//Now check if guess is same as generated
if (IN_Guess == IN_RandomNum)//if guess is equal to generated number
{
Console.WriteLine("correct in {0} turns", i + 1); //if guessed correctly
guessedCorrect = true;
break; //breaking code
}
else if (IN_Guess > IN_RandomNum) //if guess is higher than generated number
{
Console.WriteLine("Too high");// if guessed number is too high
}
else //then...
{
Console.WriteLine("Too low"); // if guessed number is too low
}
if (i == 8) //on last turn display this message
{
Console.WriteLine("*YOU ONLY HAVE 1 GUESS LEFT!*"); //display this message
}
}
if (guessedCorrect)
{
Console.WriteLine("Good job... Lets try again");
}
else
{
Console.WriteLine("Better luck next timer... here we go");
}
}
}
P.S. I lost every time i tried, your game is too hard :-(
Related
I completed an exercise and wrote this code:
var random = new Random();
var number = random.Next(1, 10);
Console.WriteLine(number);
var control = 0;
for (int i = 0; i < 4; i++)
{
Console.WriteLine("Enter a number: ");
var guessedNumber = Convert.ToInt32(Console.ReadLine());
if (guessedNumber == number)
{
Console.WriteLine("You won");
control = 1;
break;
}
}
if (control == 0)
{
Console.WriteLine("You lost");
}
And the answer is this:
var number = new Random().Next(1, 10);
Console.WriteLine("Secret is " + number);
for (var i = 0; i < 4; i++)
{
Console.Write("Guess the secret number: ");
var guess = Convert.ToInt32(Console.ReadLine());
if (guess == number)
{
Console.WriteLine("You won!");
return;
}
}
Console.WriteLine("You lost!");
I have added the control variable because if I didn't even if the user guessed the number it would still display "You lost".
Can someone explain what does "return" do in the other code and why if the user guesses the correct number it doesn't display "You lost"?
The Code is as I suppose packed in a function or main.
This function has a return type.
The function here maybe looks like this:
public void NumberGuessing()
{
.... code here ....
}
With the return statement you jump directly out of this block.
As the return type of the function is void, there is no value and a simple return will jump out of the function and everything after the return statement is not executed.
The break just exits the loop, but not the function.
your function is supposed to stop when you find the correct answer so return seems more logical, it eliminates the need for your extra control variable making the code simpler to read and less error prone (e.g. for changes in the future like find two correct answers).
I'm currently in programming 101 and I've been stuck for a long time with an issue.
My assignment wants me to create a class with a bunch of methods to run with a switch case( as a menu).
If I press 1 (add passenger), it does what it's supposed to do the first time, but the second time, it just restarts the array.
I can't seem to save my answer to the array and then move on to the next spot in the array.
Would someone please explain how I'm supposed to "call" the array and save in it outside my for-loop in method add_pass?
using System;
namespace bussen
{
class buss
{
public int[] passagerare;
public int numbof_passagerare;
public void Run()
{
int nmr = 0;
do
{
Console.WriteLine("options:");
Console.WriteLine("1 add passenger");
Console.WriteLine("2 print out all passengers");
Console.WriteLine("3 calc average age");
Console.WriteLine("0 close program");
nmr = int.Parse(Console.ReadLine());
switch (nmr)
{
case 1:add_pass();
break;
case 2:all_pass();
break;
case 3:
break;
case 0:
break;
}
} while (nmr != 0);
}
public void add_pass()
{
if (passagerare.Length < 5)
{
for (int i = 0; i < passagerare.Length; i++)
{
Console.WriteLine("type age of passenger");
int numbof_passenger = int.Parse(Console.ReadLine());
passagerare[i] = numbof_passenger;
break;
}
}
else if(passagerare.Length >= 5)
{
Console.WriteLine("buss is full");
}
}
public void all_pass()
{
foreach(int index in passagerare)
{
Console.WriteLine(index);
}
}
}
class Program
{
static void Main(string[] args)
{
var minbuss = new buss();
minbuss.Run();
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
}
}
It's starting over because you're telling it to start over. The for loop starts at 0 every time.
for (int i = 0; i < passagerare.Length; i++)
{
Console.WriteLine("type age of passenger");
int numbof_passenger = int.Parse(Console.ReadLine());
passagerare[i] = numbof_passenger;
break;
}
You need to find the length of the array and append the new entry. Try using a List instead of any array.
The issue was within the add_pass method, where i used a for - loop to add passengers. each time i pressed number 1 in the menu to call the method , the loop restarted the array wich i was saving the integers to.To get this right i just called the method without a loop like shown below. Thanks everybody for your help!
public void add_pass()
{
if (numbof_passagerare < 5)
{
Console.WriteLine("how old is the passenger");
int age = int.Parse(Console.ReadLine());
passagerare[numbof_passagerare++] = age;
}
else if(numbof_passagerare == 5)
{
Console.WriteLine("buss is full!");
}
I have a dice game which holds two dice and what happens is that one game will go through and then the user will be asked if they want to play again. If, for example, they said yes three times then when they say no at the end to exit the game, they'll get an output telling them how many times they played the game. I'm having trouble coming up with the code for it.
I don't have much experience using parameters and return types(this is a beginner assignment) but I currently have a counter which adds 1. The problem is that it starts at 0 and goes to 1, and then stays there.
Here's the code I have that runs through the game:
namespace MajorAssignment1
{
class MainClass
{
public static void Main(string[] args)
{
Console.WriteLine("Hey! Welcome to Ray's Dice Game! Let's Start");
Console.WriteLine();
EvenOrOdds();
}
public static void EvenOrOdds()
{
Random rnd = new Random();
int die1 = rnd.Next(1, 10);
int die2 = rnd.Next(1, 10);
Console.WriteLine("Die 1 = {0} and Die 2 = {1}", die1, die2);
Console.WriteLine();
Console.WriteLine("You Rolled {0} and {1}", die1, die2);
Console.WriteLine();
if ((die1 + die2) % 2 == 0)
{
Console.WriteLine("Evens are better than odd.");
Console.WriteLine();
}
if ((die1 + die2) % 2 > 0 )
{
Console.WriteLine("Odds are still cool.");
Console.WriteLine();
}
Console.WriteLine("Do you want to play again? Please enter in all caps YES or NO");
String UserInput = Console.ReadLine();
var Counter = 0;
if (UserInput == "YES")
{
EvenOrOdds();
Counter = Counter + 1;
}
else
{
Console.WriteLine("The number of times the dice was thrown is:" + Counter);
Console.WriteLine();
}
}
public static void Outro()
{
Console.WriteLine("Thanks for playing! Come again!");
Console.WriteLine();
}
}
}
By calling EvenOrOdds() from within itself in order to "play again", you are effectively creating a recursive call to the function.
You are re-defining Counter within the scope of each instance of EvenOrOdds() you are calling, resulting in Counter always ending up as 1.
One easy option is to move the definition of Counter out into a class-level variable, which then means it will be shared between all your calls to EvenOrOdds()
class MainClass
{
//class-level static variable
private static int Counter;
public static void Main(string[] args)
{
Console.WriteLine("Hey! Welcome to Ray's Dice Game! Let's Start");
Console.WriteLine();
EvenOrOdds();
}
// rest of code here
Which then means you can remove the definition of Counter within your EvenOrOdds() code. Now when you increment Counter it is updating the class-level variable, which will result in your expected Counter behaviour.
Console.WriteLine("Do you want to play again? Please enter in all caps YES or NO");
String UserInput = Console.ReadLine();
if (UserInput == "YES")
{
//increment the counter first
Counter = Counter + 1;
//then call the method again for a new game
EvenOrOdds();
}
Also you could change "Counter = Counter + 1;" line you use the inline ++ increment operator: "Counter++ ;" which will do the same thing.
Note: There are other ways to implement this type of "play again" functionality which would be better, such as using loops etc, but without rewriting what you have already done significantly my advice above will suffice as a minor change that achieves what you want to do. Good luck!
Edit: Updated to increment Counter first, before calling EventOrOdds() again - which results in Counter being correctly incremented for each game played.
Problem with your code is that you are calling EvenOrOdds() recursively, and counter never increments. Moreover, you are doing simple things in a complicated way, I have simplified few things.
Working code:
using System;
public class diceCounter
{
public static void Main(string[] args)
{
String UserInput;
int Counter =1;
Console.WriteLine("Hey! Welcome to Ray's Dice Game! Let's Start");
Console.WriteLine();
do
{
EvenOrOdds();
Console.WriteLine("Do you want to play again? Please enter in all caps YES or NO");
UserInput = Console.ReadLine();
if (UserInput.Equals("YES"))
{
Counter++;
EvenOrOdds();
}
}while(!(UserInput.Equals("NO")));
Console.WriteLine("The number of times the dice was thrown is: " + Counter);
Outro();
}
public static void EvenOrOdds()
{
Random rnd = new Random();
int die1 = rnd.Next(1, 10);
int die2 = rnd.Next(1, 10);
Console.WriteLine("Die 1 = {0} and Die 2 = {1}", die1, die2);
Console.WriteLine();
Console.WriteLine("You Rolled {0} and {1}", die1, die2);
Console.WriteLine();
if ((die1 + die2) % 2 == 0)
{
Console.WriteLine("Evens are better than odd.");
Console.WriteLine();
}
if ((die1 + die2) % 2 > 0 )
{
Console.WriteLine("Odds are still cool.");
Console.WriteLine();
}
}
public static void Outro()
{
Console.WriteLine("\nThanks for playing! Come again!\n");
}
}
I can come up with two solutions
1) use a private variable at class level. Remember to remove the definition for counter at your method
class MainClass {
private static int Counter = 0;
...
}
2) send a ref parameter to your method
public static void EvenOrOdds(ref int counter)
and in main
EventOrOdds(counter). the same goes for your recursion
I'm new to Programming. Now I have to learn C# List Items.
My Expectation:
Create an Empty List
Get the Input value for this list from the user through the console
Window.
My Program:
using System;
using System.Collections.Generic;
namespace Indexof_in_List
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Implementation of IndexOf Method with List");
Console.WriteLine();
//If the user entered empty value or nothing in the console window, the window will exit automatically
//Create an Empty List
List<int> name = new List<int>();
Console.WriteLine("Enter the Input values for the List");
//Get the Inputs for the List from the Console Window
for (int n = 0; n < name.Count; n++)
{
bool check;
string input = Console.ReadLine();
check = int.TryParse(input, out int val);
if (check)
{
name[n] = val;
}
else
{
Environment.Exit(0);
}
}
//Implement Index of any number in the list items which you have entered to the console
Console.WriteLine("The Index of value 10 is = {0}",name.IndexOf(10));
Console.WriteLine();
Console.WriteLine("The Index of value 1000 is ={0}", name.IndexOf(1000));
Console.WriteLine();
Console.ReadKey();
}
}
}
Output:
Could Anyone Tell me the solution for this C# Logic? And also tell me the reason for this failure?
And Tell me, whether my Logic is correct or not?
Your code has a few issues:
Count retrieves the current number of items in your list.
You have created your list using the default constructor, so the Capacity is also 0. Because of this you can't loop from 0 to name.Capacity.
You are trying to add items using an index. You can only access existing items using the name[index] syntax.
The simplest solution is to initialize the list as you are, and simply add items:
List<int> name = new List<int>();
for (int i = 0; i < 10; ++i)
{
bool check;
string input = Console.ReadLine();
check = int.TryParse(input, out int val);
if (check)
{
name.Add(val);
}
else
{
Environment.Exit(0);
}
}
This will read 10 numbers one after the other and add them to the list.
Thank you for your valuable Comments. Finally, I have done the final changes based on your feedback.
My Code:
using System;
using System.Collections.Generic;
namespace Indexof_in_List
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Implementation of IndexOf Method with List");
Console.WriteLine();
//Create an Empty List
List<int> name = new List<int>();
//If the user entered empty value or nothing in the console window, the window will exit automatically
Console.WriteLine("Enter the Input values for the List");
//Get the Inputs for the List from the Console Window
for (int n=0;n<5;n++)
{
bool check=false;
string input = Console.ReadLine();
check = int.TryParse(input, out int val);
if (check)
{
name.Add(val) ;
}
else
{
Environment.Exit(0);
}
}
if (name.Count != 0)
{
//Implement Index of any number in the list items which you have entered to the console
int index1 = name.IndexOf(10);
Console.WriteLine("The Index of value 10 is = {0}", name.IndexOf(10));
if (index1!=-1)
{
Console.WriteLine("The number 10 found in the List");
}
else
{
Console.WriteLine("The Number 10 found in the List");
}
int index2 = name.IndexOf(1000);
Console.WriteLine("The Index of value 1000 is ={0}", name.IndexOf(1000));
if (index2 != -1)
{
Console.WriteLine("The number 1000 found in the List");
}
else
{
Console.WriteLine("The Number 1000 not found in the List");
}
Console.WriteLine();
}
Console.ReadKey();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Pi_szamlalo
{
class Program
{
static void Main(string[] args)
{
int limit = 100;
List<int> prime = new List<int>();
prime.Add(2);
for (int number = 3; number <= limit; number = number + 1)
{
foreach(int prime2 in prime) //here is the error at "in"
{
if (number % prime2 == 0)
{
Console.WriteLine(number + " is not a prime");
}
else
{
Console.WriteLine(number + " is a prime");
prime.Add(number);
}
}
}
Console.ReadKey();
}
}
}
The idea would be that the program tries to divide all the whole numbers to the limit with the already known primes. If the remainder is zero in one of the cases, the program will move on to the next.
However, if the program could not find a prime number in the list of primes, it will add it to the list, and say it's a prime.
So, in Visual Studio 2013, there are no sign of errors, except the crash.
Here is the error message The Error message
It is in hungarian, it says something like this:
The list has been modified, it may be that the operation cannot be runned.
Here's a working example taking into account my comment above: you need to run through the whole list of primes before deciding if a number is prime - currently you're writing whether it is or isn't a prime each time you test it: you can only determine that when you've finished testing.
class Program
{
static void Main(string[] args)
{
int limit = 100;
List<int> prime = new List<int>();
prime.Add(2);
for (int number = 3; number <= limit; number = number + 1)
{
bool isPrime = true;
foreach (int prime2 in prime)
{
if (number % prime2 == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
{
Console.WriteLine(number + " is a prime");
prime.Add(number);
}
else
{
Console.WriteLine(number + " is not a prime");
}
}
}
}