C# code issue - Code not working properly - c#

I wrote a basic number guessing game from C#. It seems to return the 3rd option ("Wrong choice! Please try again.") every time no matter what var c is chosen by the user. I was trying with characters (s instead of 1 and w instead of 2 etc with c as a string) but it gave the same results. Not sure where it's going bad.
using System;
namespace Challanges
{
class Program
{
static int guess = 500;
static int low = 1;
static int high = 1000;
static bool cont = false;
static void Guess() //guesses and adjusts variables according to input.
{
int c;
Console.WriteLine("Is your number greater or less than: " + guess + Environment.NewLine + "If it is less than, press 1; if it is greater, press 2." + Environment.NewLine + "If it is your number, press 3.");
c = Convert.ToInt32(Console.Read());
if (c == 1)
{
high = 500;
guess = low + high / 2;
}
else if (c == 2)
{
low = 500;
guess = low + high / 2;
}
else if (c == 3)
{
Console.WriteLine("Congratulations!! We found your number!");
cont = true;
}
else
{
Console.WriteLine("Wrong choice! Please try again.");
Console.ReadKey();
}
}
static void Main(string[] args)
{
Console.WriteLine("Hello World!" + Environment.NewLine + "Let's play a guessing game. Think of a number between 1 and 1000." + Environment.NewLine + "Type your number :)");
int x = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Your number is: " + x + Environment.NewLine + "Too easy?");
Console.ReadKey();
Console.WriteLine("Think of a number");
if(cont == false)
{
Guess();
} else
{
Console.ReadKey();
}
}
}
}

As mentioned in the comments before, Console.Read() returns a character code. The character code for the number 1 is 49, thus your conditions fail and the else block is executed.
What you wanted to do was use Console.ReadLine()which returns a string instead of character codes. If you cast that string into an Int32 you should be able to evaluate your conditions correctly.

Related

How do I detect an infinite loop occuring in my code?

So my code is to check if a given number is a 'happy number'. It squares each digit of the number, adds them and continues to do so until either the result of the addition is 1 (which means it is a happy number) or until it results in a 4 (which means it is not a happy number).
What's happening is that there are many numbers which cause an infinite loop (therefore meaning they are not a happy number) and I'm wondering how I would construct my code so that it will detect when there's an infinite loop occuring? I have some ideas but all flawed.
My code is as follows:
using System;
namespace Happy_numbers_problem
{
class Program
{
static int HappyNumbers(string Number)
{
string Output = Number;
while ((Convert.ToInt32(Output) != 1) && (Convert.ToInt32(Output) != 4))
{
string Result2 = "0";
for (int Index = 0; Index < Output.Length; Index++)
{
string Character = Output.Substring(Index, 1);
int Calc = Convert.ToInt32(Character);
int Result = Calc * Calc;
//Adding Result2 and Result, then turning it into a string.
Result2 = Convert.ToString(Convert.ToInt32(Result2) + Result);
if (Index == (Output.Length) - 1)
{
Output = Result2;
}
}
}
return Convert.ToInt32(Output);
}
static void Main(string[] args)
{
Console.WriteLine("Please enter a number");
string Number = Console.ReadLine();
int Output = HappyNumbers(Number);
if (Output == 1)
{
Console.WriteLine(Number + " is a happy number");
}
else if (Output == 4)
{
Console.WriteLine(Number + " is not a happy number");
}
else
{
Console.WriteLine(Number + " is not a happy number");
}
}
}
}
The problem resides in your while condition. If your output needs to be 1 or 4 to break out of the loop and deliver the output to latter be analysed, you have to use the operator or || instead of the operator and &&.

how to output the contents of the list

essentially I'm making a guessing game for an assignment but as I try to output the list it comes out as
System.Collections.Generic.List`1[System.Int32]
System.Collections.Generic.List`1[System.Int32]
essentially I just need to store a users guess number and their attempt number so that once they guess the correct number it will display it as
"YOU WON, the number was ___ and here are your attempts
you chose 45
you chose 54
you chose 32
you chose ___
using System;
using System.Collections.Generic;
namespace main__4_8_2021_
{
class Program
{
public static void Main(string[] args)
{
while (true)
try
{
int NumberOfTries = 0;
Console.WriteLine("Guess a number between 1 and 100");
int number = Convert.ToInt32(Console.ReadLine());
List<int> mylist2 = new List<int>(number);
List<int> mylist = new List<int>(NumberOfTries);
int rng = new Random().Next(1, 101);
if (number == rng)
{
Console.WriteLine("Your guess was correct! The number was " + number + "!");
Console.WriteLine(mylist);
Console.WriteLine(mylist2);
break;
}
else if (number > rng)
{
NumberOfTries++;
Console.WriteLine("Your guess was too high ");
Console.WriteLine(mylist);
Console.WriteLine(mylist2);
Console.WriteLine("you now have done " + NumberOfTries + " Tries");
}
else if (number < rng)
{
NumberOfTries++;
Console.WriteLine("too low, ");
Console.WriteLine(mylist);
Console.WriteLine(mylist2);
Console.WriteLine("you now have done " + NumberOfTries + " Tries");
}
Console.Write($"Try again. ");
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}
(the other console.writelines of the lists are just there for debug)
You have a number of issues with your code.
First, you don't need a counter for number of attempts, a Count property on the List is enough.
Second, you need to keep that list outside of the loop so it is not recreated each time.
Try the below
using System;
using System.Collections.Generic;
namespace main__4_8_2021_
{
class Program
{
public static void Main(string[] args)
{
List<int> mylist = new List<int>();
void PrintListContents() {
Console.WriteLine("here are your attempts");
var index = 0;
foreach(var value in mylist) {
Console.WriteLine($"{index}. You chose {value}");
index++;
}
}
while (true)
try
{
Console.WriteLine("Guess a number between 1 and 100");
int number = Convert.ToInt32(Console.ReadLine());
mylist.Add(number);
int rng = new Random().Next(1, 101);
if (number == rng)
{
Console.WriteLine("Your guess was correct! The number was " + number + "!");
PrintListContents()
break;
}
else if (number > rng)
{
NumberOfTries++;
Console.WriteLine("Your guess was too high ");
PrintListContents()
Console.WriteLine("you now have done " + myList.Count + " Tries");
}
else if (number < rng)
{
NumberOfTries++;
Console.WriteLine("too low, ");
PrintListContents()
Console.WriteLine("you now have done " + myList.Count + " Tries");
}
Console.Write($"Try again. ");
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}
Console.WriteLine(mylist);
If value is null, only the line terminator is written. Otherwise, the
ToString method of value is called to produce its string
representation, and the resulting string is written to the standard
output stream.
SOURCE https://learn.microsoft.com/en-us/dotnet/api/system.console.writeline?view=net-5.0#System_Console_WriteLine_System_Object_
this means that you actually calling the ToString method of the list. Most of the "complex" types do not overwrite the ToString method which results in just returning the string representation of Type. In your case: List<int> which is represented as System.Collections.Generic.List`1[System.Int32]
you may also want to have a look at https://learn.microsoft.com/en-us/dotnet/api/system.object.tostring?view=net-5.0

How to loop a Console.ReadLine to the infinite?

Hello i'm trying to create a calculator game but it loops only 2 times and (idk why)not til the user finds the result with input. And i'll later see how to make a random generator of numbers instead of writing them by myself in the code. Ty for helping.
Yassine
using System;
namespace G
{
class Program
{
static void Main(string[] args)
{
Calcul(2, 2);
}
static void Calcul(int nombre1, int nombre2)
{
int result = nombre1 + nombre2;
Console.WriteLine("Combien font " + nombre1 + " + " + nombre2);
int supposed = int.Parse(Console.ReadLine());
if(result != supposed)
{
Console.WriteLine("Try again!");
supposed = int.Parse(Console.ReadLine());
}
else
{
Console.Clear();
Console.WriteLine("Correct!");
}
}
}
}
You can change your if statement to a while loop whose condition is that the input does not match the result. We can also use int.TryParse with Console.ReadLine to handle cases where the user doesn't enter a valid number. This works by taking an out parameter that gets set to the parsed value if it's successful, and it returns a bool that indicates success. Perfect for a loop condition!
Then you can put the "success" message after the body of the while loop (because the only way to exit the loop is to get the correct answer). It would look something like:
static void Calcul(int nombre1, int nombre2)
{
int result = nombre1 + nombre2;
int input;
Console.Write($"Combien font {nombre1} + {nombre2} = ");
while (!int.TryParse(Console.ReadLine(), out input) || input != result)
{
Console.WriteLine("Incorrect, please try again.");
Console.Write($"Combien font {nombre1} + {nombre2} = ");
}
Console.WriteLine("Correct! Press any key to exit.");
Console.ReadKey();
}

How can I make a program loop back to the start if else is true? C#

Couldn't find any other answer on the site that covers this. If else is run and an error message is displayed, is it possible to restart the program by looping back to the start instead of restarting the console?
class Program
{
static void Main(string[] args)
{
int User;
int Array;
StreamWriter outfile = new StreamWriter("C://log.txt");
Console.WriteLine("Input an number between 1 and 100");
User = Convert.ToInt32(Console.ReadLine());
if (User < 101 && User > 0)
{
for (Array = 1; Array <= User; Array++)
{
Console.WriteLine(Array + ", " + Array * 10 * Array);
outfile.WriteLine(Array + ", " + Array * 10 * Array);
}
{
Console.WriteLine("Press Enter To Exit The Console");
outfile.Close();
Console.ReadLine();
}
}
else
{
Console.WriteLine("Sorry you input an invalid number. ");
Console.ReadLine();
}
}
}
Sorry! To be more clear I need to make the Program start again if the user inputs an invalid number
Thanks for the help!
You can do this instead
User = Convert.ToInt32(Console.ReadLine());
while (User >= 101 || User <= 0)
{
Console.WriteLine("Sorry you input an invalid number. ");
User = Convert.ToInt32(Console.ReadLine());
}
An easy way of doing this is placing your code inside a while loop, so that the code keeps repeating. The only way to exit the loop would be for the condition you just set in the if clause to be true. So something along the lines of:
class Program
{
static void Main(string[] args)
{
int User;
int Array;
bool isUserWrong = true; //This is a flag that we will use to control the flow of the loop
StreamWriter outfile = new StreamWriter("C://log.txt");
while(isUserWrong)
{
Console.WriteLine("Input an number between 1 and 100");
User = Convert.ToInt32(Console.ReadLine());
if (User < 101 && User > 0)
{
for (Array = 1; Array <= User; Array++)
{
Console.WriteLine(Array + ", " + Array * 10 * Array);
outfile.WriteLine(Array + ", " + Array * 10 * Array);
}
isUserWrong = false; // We signal that we may now leave the loop
}
else
{
Console.WriteLine("Sorry you input an invalid number. ");
Console.ReadLine();
//Note that here we keep the value of the flag 'true' so the loop continues
}
}
Console.WriteLine("Press Enter To Exit The Console");
outfile.Close();
Console.ReadLine();
}
}

Guessing Game Number Issue

Before I get down-voted for the extensive code, I feel it's necessary for a solution to present itself.
I've made alterations to the program's code from the help previously presented, but I still seem to be falling into the problem that the random number number is either not being properly compared (I've had examples where number is '5' and the user's guess is '5', but I'm still getting a comment that "You're quite far off! Try again." meaning it's falling into else if (userinputcalc > 4 | userinputcalc < 10)...
So, at this stage the issue seems to lie within the comparison of number and the userinput, leading to confusing output messages.
I'm probably missing something obvious here, despite being sure it's around the loop of comparing number and userinput but I've been looking at this code and seeing nothing.
Any help is greatly appreciated, as always.
public void GuessingGame()
{
string username; // Will be the user's chosen name for program interaction
int guessesleft = 0;// Stands for the number of guesses left (out of 3)
int spaceaway = 0; // Space from the guess and the random number, if not correct guess
int roundcount = 1; //Started at 1 for the sake of the user interface - aesthetics
int number = 0; // Current value of the random number
int userinput = 0; //User input is the guess the user makes during the guessing game
int userinputcalc = 0;// calculation of guess and random number, when added to spaceaway calculation
int answersright = 0; // Number of times the user guessed the number correctly
Random rndm = new Random(); // Initialises a new class of random, which'll be used to simulate the random number
Console.WriteLine("Welcome to Guessing Game!");
Console.WriteLine("");
Console.WriteLine("Please press any button to continue.");
Console.ReadLine();
Console.WriteLine("What's your name?");
username = (Console.ReadLine());
//If you're wondering at all, the "You must guess what it is inthree tries." is intentional, since it was showing double-spaced in the command prompt
Console.WriteLine("Well, " + username + ", I am thinking of a number from 1 to 10. You must guess what it is inthree tries.");
Console.WriteLine("");
{
do
{
Console.WriteLine("Round" + roundcount); //Displays the which round (out of 10) to the user
guessesleft = 3; //The remaining guesses left for the user
do
{
number = rndm.Next(10) + 1; // int number is set to a random number between 1 and 10
Console.WriteLine("Please enter a guess:");
userinput = int.Parse(Console.ReadLine());
guessesleft = guessesleft - 1;
if (userinput == number)
{
//Below, once you've guessed right, you will have this message displayed in the console
Console.WriteLine("You guessed " + number + " *RIGHT*!");
answersright = answersright + 1;
guessesleft = 0;// No point need to guess further on something you've guessed correctly - saves correct answer value exploit
}
else if (userinput < 1 || userinput > 10) // If user's guess is less than 1 or more than 10, then out of range. Counts as a guess.
{
Console.WriteLine("You guessed " + userinput + "! and it was incorrect!");
Console.WriteLine("This is outside of the range of numbers between 1-10 ");
}
else if (userinput != number) // while the user's guess does not equal the number
{
{
// userinputcalc = Math.Abs(number - userinput);
//Left out as I was getting abnormal run-time outputs and the math showed up wrong.
//(Example: RND No. = 5 Userinput = 5 Output: "Incorrect" "Hot")
spaceaway = (number - userinput); // Works out how far from the random no. the user's guess is.
// If user guesses 6 and random no. is 5, answer will be -1 this makes the value +ve and allows output to be shown without error
if (spaceaway < 0)
{
spaceaway = (spaceaway * -1);
userinputcalc = spaceaway;
}
else if (spaceaway > 0)
{
userinputcalc = spaceaway;
}
}
{
if (userinputcalc < 2)
{
Console.WriteLine("You guessed " + userinput + "! and it was wrong!");
Console.WriteLine("Hot");
}
else if
(userinputcalc < 3)
{
Console.WriteLine("You guessed " + userinput + "! and it was wrong!");
Console.WriteLine("Warm");
}
else if
(userinputcalc < 4)
{
Console.WriteLine("You guessed " + userinput + "! and it was wrong!");
Console.WriteLine("Cold");
}
else if (userinputcalc > 4 | userinputcalc < 10)
{
Console.WriteLine("You guessed " + userinput + "! and it was wrong!");
Console.WriteLine("You're quite far off! Try again.");
}
}
}
} while (guessesleft > 0);
Console.WriteLine("");
Console.WriteLine("The number was, "+number+"!");
Console.WriteLine("");
roundcount = roundcount + 1;
} while (roundcount < 11);
Console.WriteLine("Well, " + username + ". " + "You guessed correctly, " + answersright + " times!");
}
}
}
}
OK I think theres quite a few issues here (some are off topic but definitely worth mentioning)..
I wouldn't advise using while loops to check for specific inputs
For example:
Instead of roundCount != 11 use roundCount < 11
Then there is less chance of forever getting stuck in a loop
You should declare Random outside of your loops otherwise you run the risk of just getting the same numbers ("randomly")
You reset the number to a new number after every guess so the user doesn't have a chance to guess the right number
With all this being said, I think the Math.Abs was correct if you are trying to find the distance away from the number.. I wouldnt use less than two though as that would mean only numbers that are 1 away from the answer are "hot"
Note: Answer is based off question revision #5
Update
Doesn't seem like you were far off but you still reset the number every loop
number = rndm.Next(10) + 1; //Insert here
do
{
//Displays the which round (out of 10) to the user
Console.WriteLine("Round" + roundcount);
guessesleft = 3; //The remaining guesses left for the user
do
{
// Remove this -- number = rndm.Next(10) + 1;
I think this is what you want,please try it:
static int guessesleft;
static Random ran = new Random();
static int MagicNumber;
static string UserInput;
static void Main(string[] args)
{
ConsoleKeyInfo ci = new ConsoleKeyInfo();
do
{
guessesleft = 3;
UserInput = "";
Console.Clear();
string username;
int guesscount = 1;
Console.WriteLine("Welcome to Jackie's Guessing Game!");
Console.WriteLine("");
Console.WriteLine("Please press any button to continue.");
Console.ReadLine();
Console.WriteLine("What's your name?");
username = (Console.ReadLine());
//If you're wondering at all, the "You must guess what it is inthree tries." is intentional, since it was showing double-spaced in the command prompt
Console.WriteLine("Well, " + username + ", I am thinking of a number from 1 to 10. You must guess what it is inthree tries.");
Console.WriteLine("");
MagicNumber = ran.Next(1, 11);
do
{
Console.WriteLine("Please insert your " + guesscount++ + "º guess!");
UserInput = Console.ReadLine().Trim();
if (UserInput == MagicNumber.ToString())
break;
if (Math.Abs(Convert.ToInt32(UserInput) - MagicNumber) < 2)
Console.WriteLine("Hot!!");
else if(Math.Abs(Convert.ToInt32(UserInput) - MagicNumber) < 3)
Console.WriteLine("Warm!!");
Console.WriteLine("No luck , you have " + --guessesleft + "º guesses left!");
Console.WriteLine();
} while (guesscount < 4);
if (guesscount == 4)
Console.WriteLine("Sorry " + username + " no more tries,you lost!");
else
Console.WriteLine("Congratulations your guess with number " + UserInput + " is correct,the number was " + MagicNumber);
Console.WriteLine("Press Q to quit or Enter to Play again!");
ci = Console.ReadKey();
} while (ci.Key != ConsoleKey.Q);
}

Categories

Resources