Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
How do I get out of this loop?
I wrote a program that checks to see if corresponding places in the numbers are the same total. The console output should be true or false. I wrote that, and then added the top part that interacts with the user, and now I get stuck in a loop. How do I get out of it?
using System;
namespace DeliverablePart1
{
class DeliverablePart1
{
static void Main(string[] args)
{
string gameAnswer;
bool repeat1 = true, repeat2 = true;
while (repeat1 == true)
{
repeat2 = true;
Console.WriteLine("Would you like to compare 2 numbers to see if their corresponding place is same total?");
gameAnswer = Console.ReadLine();
while (repeat2 == true)
{
if (gameAnswer == "yes" || gameAnswer == "yes" || gameAnswer == "YES")
{
Console.WriteLine("Please enter a three digit whole number");
string firstValue = Console.ReadLine();
int firstNumber = ValidInteger(firstValue);
Console.WriteLine("Please enter a second three digit whole number");
string secondValue = Console.ReadLine();
int secondNumber = ValidInteger(secondValue);
repeat1 = false;
repeat2 = false;
}
else if (gameAnswer == "no" || gameAnswer == "No" || gameAnswer == "NO")
{
Console.WriteLine("Okay, exiting now");
repeat1 = false;
repeat2 = false;
}
else
{
Console.WriteLine("I do not understnad what you have said");
repeat2 = false;
}
void Add(int firstNumber, int secondNumber)
{
int length1 = firstNumber.ToString().Length;
int length2 = secondNumber.ToString().Length;
string userInput;
if (length1 == length2)
{
string Answer = Convert.ToString(Compare(firstNumber, secondNumber, length1));
}
else
{
userInput = "invalid user input - Check number of digits next time.";
Console.WriteLine(userInput);
Console.ReadKey();
}
Console.ReadKey();
}
int ValidInteger(string digit1)
{
int value = 0;
string notInt = "This is not an integer.";
{
bool successfullyParsed = int.TryParse(digit1, out value);
if (successfullyParsed)
{
int firstNumber = Convert.ToInt32(value);
return value;
}
else
{
Console.WriteLine(notInt);
Console.ReadKey();
Environment.Exit(0);
return value;
}
}
}
string Compare(int a, int b, int c)
{
int lastDigitA;
int lastDigitB;
lastDigitA = (a % 10);
lastDigitB = (b % 10);
int sumStatic = lastDigitA + lastDigitB;
do
{
lastDigitA = (a % 10);
lastDigitB = (b % 10);
a = a / 10;
b = b / 10;
c--;
int sumCompare = lastDigitA + lastDigitB;
if (sumCompare != sumStatic)
{
Console.WriteLine("False");
return "False";
}
}
while (c != 0);
Console.WriteLine("True");
return "True";
}
}
}
}
}
}
From my understanding, it looks like you want the user to enter in three ints (with some input validation), and put the three ints through the Compare() function. If the function returns true, then say "True" to the console, and if it's false then say "False" to the console. If that's the case, I refactored your code into this (and it doesn't get stuck in a loop):
using System;
namespace DeliverablePart1
{
internal class DeliverablePart1
{
private static void Main(string[] args)
{
Console.WriteLine("Would you like to compare 2 numbers to see if their corresponding place is same total?");
var shouldContinue = Console.ReadLine();
if (shouldContinue != null && shouldContinue.Equals("yes", StringComparison.CurrentCultureIgnoreCase))
{
var firstNum = GetIntFromUser("Please enter a three digit whole number");
var secondNum = GetIntFromUser("Please enter a three digit whole number");
var thirdNum = GetIntFromUser("Please enter a three digit whole number");
Console.WriteLine(Compare(firstNum, secondNum, thirdNum) ? "True" : "False");
}
else
{
Console.WriteLine("Exiting");
}
// waits for the user to press a key to exit the app, so that they can see their result
Console.ReadKey();
}
/// <summary>
/// Makes the user enter in a three digit number, and exits if they say "no"
/// </summary>
/// <param name="msg">The message prompt to ask for the integer</param>
/// <returns>System.Int32., or will exit</returns>
public static int GetIntFromUser(string msg)
{
while (true)
{
Console.WriteLine(msg);
var valFromUser = Console.ReadLine()?.Trim();
if (valFromUser != null)
{
int result;
if (int.TryParse(valFromUser.Trim(), out result) && valFromUser.Length == 3)
{
return result;
}
if (valFromUser.Equals("no", StringComparison.CurrentCultureIgnoreCase))
{
Console.WriteLine("Exiting.");
Environment.Exit(0);
}
}
Console.WriteLine("Hmm, that's not a three digit number. Try again.");
}
}
public static bool Compare(int a, int b, int c)
{
var lastDigitA = a % 10;
var lastDigitB = b % 10;
var sumStatic = lastDigitA + lastDigitB;
do
{
lastDigitA = a % 10;
lastDigitB = b % 10;
a = a / 10;
b = b / 10;
c--;
var sumCompare = lastDigitA + lastDigitB;
if (sumCompare != sumStatic)
{
return false;
}
} while (c != 0);
return true;
}
}
}
Related
I need to identify if password is equal to Pin(), I don't know if the problem is comparing a method inside a method
public static string Pin(int size = 4) {
StringBuilder sb = new StringBuilder(size);
while (sb.Length < size) {
var key = Console.ReadKey(true);
if (key.KeyChar >= '0' && key.KeyChar <= '9') {
sb.Append(key.KeyChar);
Console.WriteLine('*');
}
}
return sb.ToString();
}
static void Card() {
Console.WriteLine("Enter the 4 Digits Password");
int password = int.Parse(Console.ReadLine());
if (password == Pin()) {
// Is going to do something
}
}
You cannot compare string (Pin() result) and int (password) directly. Either convert password to string string password = Console.ReadLine();, either add int.Parse to the Pin() function result.
if (password == int.Parse(Pin()))
{
// Is going to do something
}
I suggest implementation like this. For reading Pin we can put
// Since Pin is integer, let's return int, not string
public static int Pin(int size = 4) {
if (size <= 0 || size >= 9)
throw new ArgumentOutOfRangeException(nameof(size));
StringBuilder sb = new StringBuilder(size);
while (sb.Length != size) {
var position = Console.GetCursorPosition();
char letter = Console.ReadKey().KeyChar;
Console.SetCursorPosition(position.Left, position.Top);
if (letter >= '0' && letter <= '9') {
Console.Write('*');
sb.Append(letter);
}
else {
Console.Write(' ');
Console.SetCursorPosition(position.Left, position.Top);
}
}
return int.Parse(sb.ToString());
}
Let's extract ReadInteger as well:
public static int ReadInteger(string title) {
while (true) {
if (!string.IsNullOrWhiteSpace(title))
Console.WriteLine(title);
if (int.TryParse(Console.ReadLine(), out int result))
return result;
Console.WriteLine("Syntax error, incorrect integer value. Please, try again.");
}
}
Then you can use the routine as simple as
static void Card() {
int password = ReadInteger("Enter the 4 Digits Password");
if (password == Pin()){
// Is going to do something
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
using System;
namespace suma_cifrelor_unui_nr
{
class Program
{
static void Main(string[] args)
{
int n;
int suma = 0;
Console.Write("Introdu numarul ");
Console.Write("\n");
n = int.Parse(ConsoleInput.ReadToWhiteSpace(true));
while (n > 0)
{
suma = suma + n % 10;
n = n / 10;
}
Console.Write("Suma cifrelor este ==");
Console.Write(suma);
}
}
}
When I m trying to run this code the following error pops up :
"The name 'ConsoleInput' does not exist in the current context"
enter image description here
As expected ConsoleInput is a helper class so I did some google search,
And that's land me to convert code from c++ to c# and i found that words "with the 'ConsoleInput' helper class added by our converter", so try to check google before ask next time.
internal static class ConsoleInput
{
private static bool goodLastRead = false;
internal static bool LastReadWasGood
{
get
{
return goodLastRead;
}
}
internal static string ReadToWhiteSpace(bool skipLeadingWhiteSpace)
{
string input = "";
char nextChar;
while (char.IsWhiteSpace(nextChar = (char)System.Console.Read()))
{
//accumulate leading white space if skipLeadingWhiteSpace is false:
if (!skipLeadingWhiteSpace)
input += nextChar;
}
//the first non white space character:
input += nextChar;
//accumulate characters until white space is reached:
while (!char.IsWhiteSpace(nextChar = (char)System.Console.Read()))
{
input += nextChar;
}
goodLastRead = input.Length > 0;
return input;
}
internal static string ScanfRead(string unwantedSequence = null, int maxFieldLength = -1)
{
string input = "";
char nextChar;
if (unwantedSequence != null)
{
nextChar = '\0';
for (int charIndex = 0; charIndex < unwantedSequence.Length; charIndex++)
{
if (char.IsWhiteSpace(unwantedSequence[charIndex]))
{
//ignore all subsequent white space:
while (char.IsWhiteSpace(nextChar = (char)System.Console.Read()))
{
}
}
else
{
//ensure each character matches the expected character in the sequence:
nextChar = (char)System.Console.Read();
if (nextChar != unwantedSequence[charIndex])
return null;
}
}
input = nextChar.ToString();
if (maxFieldLength == 1)
return input;
}
while (!char.IsWhiteSpace(nextChar = (char)System.Console.Read()))
{
input += nextChar;
if (maxFieldLength == input.Length)
return input;
}
return input;
}
}
using System;
namespace suma_cifrelor_unui_nr
{
internal static class ConsoleInput
{
static void Main(string[] args)
{
int n;
int suma = 0;
Console.Write("Introdu numarul ");
Console.Write("\n");
n = int.Parse(ConsoleInput.ReadToWhiteSpace(true));
while (n > 0)
{
suma = suma + n % 10;
n = n / 10;
}
Console.Write("Suma cifrelor este ==");
Console.Write(suma);
}
private static ReadOnlySpan<char> ReadToWhiteSpace(bool v)
{
throw new NotImplementedException();
}
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
using System;
namespace Test
{
class Program
{
static void Main(string[] args)
{
int num1 = int.Parse(args[0]);
int num2 = int.Parse(args[1]);
bool GameOver = false;
int turn = 3;
Random random = new Random();
int answer = random.Next(num1, num2);
// string input = "";
Console.WriteLine("Hello, welcome to the guess a number challenge");
while (!GameOver)
{
if (turn != 0)
{
turn--;
Console.WriteLine($"Please Select number between {num1} to {num2}:");
int SelectedNumber = int.Parse(Console.ReadLine());
if (SelectedNumber < answer && SelectedNumber >= num1)
{
System.Console.WriteLine("Almost there, just the number is too small\n");
} else if (SelectedNumber > answer && SelectedNumber <= num2)
{
System.Console.WriteLine("Your number is too big\n");
} else if(SelectedNumber == answer)
{
System.Console.WriteLine("CONGRATULATIONS!!!! You guess it right\n");
GameOver = true;
retry();
} else
{
System.Console.WriteLine("Your number is out of range\n");
}
} else
{
System.Console.WriteLine($"GAME OVER!!!! The answer is {answer}");
GameOver = true;
retry();
}
void retry() {
System.Console.WriteLine("Would you like to retry? Y/N");
string input = Console.ReadLine();
string ConsoleInput = input.ToLower();
if(ConsoleInput == "y")
{
GameOver = false;
turn = 3;
} else if(ConsoleInput == "n")
{
GameOver = true;
} else
{
Console.WriteLine("Invalid input");
retry();
}
}
}
}
}
}
Hello all, just want to ask a question.
I tried to build "guess a number" game in terminal, where player has to guess a number based on the number range given.
I tried to make the answer randomly generated, thus the Random class.
and the answer will be randomized after retry.
The problem is, after each retry, the answer is still the same.
I am not sure where did I did wrong.
Thanks for the help, and sorry for the noob question.
i edited out your code
using System;
namespace Test
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter num1");
int num1 = int.Parse(Console.ReadLine());
Console.WriteLine("Enter num2");
int num2 = int.Parse(Console.ReadLine());
bool GameOver = false;
int turn = 3;
Random random = new Random();
int answer = random.Next(num1, num2);
// string input = "";
Console.WriteLine("Hello, welcome to the guess a number challenge");
while (!GameOver)
{
if (turn != 0)
{
turn--;
Console.WriteLine($"Please Select number between {num1} to {num2}:");
int SelectedNumber = int.Parse(Console.ReadLine());
if (SelectedNumber < answer && SelectedNumber >= num1)
{
System.Console.WriteLine("Almost there, just the number is too small\n");
}
else if (SelectedNumber > answer && SelectedNumber <= num2)
{
System.Console.WriteLine("Your number is too big\n");
}
else if (SelectedNumber == answer)
{
System.Console.WriteLine("CONGRATULATIONS!!!! You guess it right\n");
GameOver = true;
retry();
}
else
{
System.Console.WriteLine("Your number is out of range\n");
}
}
else
{
System.Console.WriteLine($"GAME OVER!!!! The answer is {answer}");
GameOver = true;
retry();
}
void retry()
{
System.Console.WriteLine("Would you like to retry? Y/N");
string input = Console.ReadLine();
string ConsoleInput = input.ToLower();
if (ConsoleInput == "y")
{
answer = random.Next(num1, num2);
GameOver = false;
turn = 3;
}
else if (ConsoleInput == "n")
{
GameOver = true;
}
else
{
Console.WriteLine("Invalid input");
retry();
}
}
}
}
}
}
You need an outside loop in order to start a new game after the end:
See below a skeleton program with the necessary control flow.
class Program
{
static void Main(string[] args)
{
bool retry = false;
do
{
// start of game
bool gameOver = false;
int turn = 3;
do
{
// game here
// set gameOver when guess is corrent
turn--;
} while (turn>0 && !gameOver);
// post game scores
// ask to retry
} while (retry);
// end here
}
}
i want to check if entered string is a Integer or not for example
12 = True
+12 = True
-5 = True
4.4 = False
4as = False
I make it using int.TryParse but what I want is to using ASCII without using int.TryParse
string str;
int strint;
int strintoA;
bool flag = false;
while (flag == false)
{
Console.Write("Enter a Number : ");
str = Console.ReadLine();
flag = int.TryParse(str, out strint);
if (flag == false)
{
Console.WriteLine("Please Enter Numbers Only.");
}
else
{
strintoA = strint;
Console.WriteLine("Entered String: " + str + " is a Number!" );
break;
}
}
Console.ReadKey();
You could also use regular expressions:
var regex = new Regex(#"^[-+]?\d+$");
var str = Console.ReadLine();
if (regex.IsMatch(str))
{
Console.WriteLine($"{str} is a number!");
}
check the first char for -|+|digit, check rest isDigit
for (int i = 0; i < str.Length; i++)
{
var c = str[i];
if (i == 0)
{
if (!(c == '+' || c == '-' || char.IsDigit(c)) {
return false;
}
}
if (!char.IsDigit(c)) return false;
}
return true;
why dont use:
if(intString[0] == '+' || intString[0] == '-') intString = intString.Substring(1, intString.Length - 1);
bool isNumber = intString.All(char.IsDigit);
Not sure why you don't want to use int.TryParse but the following code should do:
static bool IsValidInteger(string s)
{
var leadingSignSeen = false;
var digitSeen = false;
var toParse = s.Trim();
foreach (var c in toParse)
{
if (c == ' ')
{
if (digitSeen)
return false;
}
else if (c == '+' || c == '-')
{
if (leadingSignSeen || digitSeen)
return false;
leadingSignSeen = true;
}
else if (!char.IsDigit(c))
return false;
else
{
digitSeen = true;
}
}
return true;
}
This will accept any integer with leading sign and leading and trailing spaces. Whitespaces between leading sign and digits are also accepted.
FYI: You can refactor your code to simplify it for exactly the same functional output:
void Main()
{
int result;
Console.Write("Enter a Number : ");
while (!int.TryParse(Console.ReadLine(), out result))
{
Console.WriteLine("Please Enter Numbers Only.");
Console.Write("Enter a Number : ");
}
Console.WriteLine($"Entered String: {result} is a Number!");
Console.ReadKey();
}
If you have a good reason to not use int.TryParse (e.g. it's lacking some functionality, or this is an exercise where you've been asked to write your own) you could use the above replacing int.TryParse with a call to IsNumericCustom, assuming the below signature (or change type int to whatever data type you need to handle).
public bool IsNumericCustom(string input, out int output)
{
//...
}
Or if you only care about whether the value's numeric and not the parsed value:
void Main()
{
string result;
Console.Write("Enter a Number : ");
//while (!int.TryParse((result = Console.ReadLine()), out _))
while (!IsNumericCustom((result = Console.ReadLine()))
{
Console.WriteLine("Please Enter Numbers Only.");
Console.Write("Enter a Number : ");
}
Console.WriteLine($"Entered String: {result} is a Number!");
Console.ReadKey();
}
public bool IsNumericCustom(string input)
{
//...
}
As for the logic in the IsNumericCustom, it really depends on what you're hoping to achieve / why int.TryParse / decimal.TryParse etc aren't appropriate. Here's a couple of implementations (using different function names).
using System.Text.RegularExpressions; //https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex?view=netframework-4.7.2
//...
readonly Regex isNumeric = new Regex("^[+-]?\d*\.?\d*$", RegexOptions.Compiled); //treat "." as "0.0", ".9" as "0.9", etc
readonly Regex isInteger = new Regex("^[+-]?\d+$", RegexOptions.Compiled); //requires at least 1 digit; i.e. "" is not "0"
readonly Regex isIntegerLike = new Regex("^[+-]?\d*\.?\0*$", RegexOptions.Compiled); //same as integer, only 12.0 is treated as 12, whilst 12.1 is invalid; i.e. only an integer if we can remove digits after the decimal point without truncating the value.
//...
public bool IsNumeric(string input)
{
return isNumeric.IsMatch(input); //if you'd wanted 4.4 to be true, use this
}
public bool IsInteger(string input)
{
return isInteger.IsMatch(input); //as you want 4.4 to be false, use this
}
public bool IsIntegerLike(string input)
{
return isIntegerLike.IsMatch(input); //4.4 is false, but both 4 and 4.0 are true
}
From your requirements it appears that you want to use ASCII code in order to assert whether the string entered is numeric or not.
This is the code I have come up with:
string str;
var index = 1;
int strintoA = 0;
bool isNegative = false;
//ASCII list of numbers and signs
List<int> allowedValues = new List<int> { 43, 45, 48, 49, 50, 51, 52, 53, 54, 55, 56,
57 };
bool flag = false;
while (!flag)
{
Console.WriteLine("Enter a Number : ");
str = Console.ReadLine();
if (str.Count(item => allowedValues.Contains((int)item)) == str.Count())
{
foreach (var item in str.Reverse())
{
if (item != 43 && item != 45)
{
strintoA += index * (item - 48);
index = index * 10;
}
else if(item == 45)
{
isNegative = true;
}
}
if(isNegative)
{
strintoA *= -1;
}
Console.WriteLine("Entered String: " + str + " is a Number!");
flag = true;
}
else
{
Console.WriteLine("Please Enter Numbers Only.");
}
}
Console.ReadKey();
}
The allowedValues list contains the ASCII representation of numeric values and allowed signs(+ and -). The foreach loop will regenerates the int value inserted.
Hope it helps.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
enter code here`namespace fuel_consumption {
class Program {
// Program Reset & exit method at the end of program
static bool DoItAgain()
{
bool startAgain = true;
string reply = "";
Console.Write("Start Over? (Y or N): ");
reply = Console.ReadLine();
reply = reply.ToUpper();
if (reply != "Y")
{
startAgain = false;
}
return startAgain;
}//End DoItAgain method
//Startup Screen method
static void WelcomeMessage() {
Console.WriteLine("\n\n\tWelcome to the Fuel Consumption Calculator\n\n\t");
}// End startup Screen method
//Begin user input method for Number of Litres
static int InputLitres() {
string userInput = "";
int selection = 0;
int minLitres = 20;
bool inValid = true;
//User Input Message
while (inValid) {
Console.Write("\nEnter the amount of litres consumed: ");
the program keeps asking this question over and over, about 5 times infact.
userInput = Console.ReadLine();
if (int.TryParse(userInput, out selection))
if (selection < minLitres) {
// Deliver Error Message to User
Console.Write("\nPlease Enter an amount 20 litres or above\n\n Please Try Again:\n");
}
else {
inValid = false;
}
}
//return the value entered by the user
return selection;
}//end InputLitres
//Begin InputKM method
static int InputKM() {
//set user input varibles
string userInput = "";
int selection = 0;
int inputLitres = InputLitres();
int minKms = 8 * inputLitres;
bool inValid = true;
while (inValid) {
Console.Write("\nEnter Kilometres Travelled: ");
Then it asks this question a few times aswell
userInput = Console.ReadLine();
if (int.TryParse(userInput, out selection))
if (selection < minKms) {
//Deliver Error Message to user and redirect back to user input of kms
Console.WriteLine("\n Minimum Kms is {0:f2} Kilometres, Please Enter a value of {0:f2} or higher", minKms);
}
else {
inValid = false;
}
}
//return the KM Value
return selection;
}//End Input Kms
static double consumptionCalculation() {
int litres;
int kms;
double litresFormula;
double formulaResult;
//Define Base Varibles
formulaResult = 0.0;
litresFormula = 0.0;
litres = InputLitres();
kms = InputKM();
//Calculate fuel consumption in litres per 100km
litresFormula = (double)litres * 100;
formulaResult = (double)litresFormula / kms;
{
//Return the result value
return formulaResult;
}
}
//Print results method
static void PrintResults() {
double kmResult = consumptionCalculation();
Console.WriteLine("\n\n\tYour Fuel Consumption is {0} Litres per 100 Kilometres", kmResult);
}
//Start Program Loop Method
static void ProgramLoop() {
bool startAgain = true;
//Loop through each user Input Method
InputLitres();
InputKM();
consumptionCalculation();
PrintResults();
startAgain = DoItAgain();
}
static void Main(string[] args) {
WelcomeMessage();
ProgramLoop();
}
}
}
Can anyone give me an idea of where i am going wrong? I just need it to ask those questions once, return the value. Please make it simple as I am new to this. Thanks
This is the kind of thing you need to do.
void Main()
{
WelcomeMessage();
ProgramLoop();
}
static void ProgramLoop()
{
bool startAgain = true;
while (startAgain)
{
int litres = InputLitres();
int kms = InputKM(litres);
double consumption = consumptionCalculation(litres, kms);
PrintResults(consumption);
startAgain = DoItAgain();
}
}
static bool DoItAgain()
{
Console.Write("Start Over? (Y or N): ");
string reply = Console.ReadLine();
reply = reply.ToUpper();
return reply.ToUpper() == "Y";
}
static void WelcomeMessage()
{
Console.WriteLine("\n\n\tWelcome to the Fuel Consumption Calculator\n\n\t");
}
static int InputLitres()
{
int selection = -1;
int minLitres = 20;
bool invalid = true;
while (invalid)
{
Console.Write("\nEnter the amount of litres consumed: ");
if (int.TryParse(Console.ReadLine(), out selection))
{
invalid = selection < minLitres;
if (invalid)
{
Console.Write("\nPlease Enter an amount 20 litres or above\n\n Please Try Again:\n");
}
}
}
return selection;
}
static int InputKM(int litres)
{
int selection = -1;
int minKms = 8 * litres;
bool invalid = true;
while (invalid)
{
Console.Write("\nEnter Kilometres Travelled: ");
if (int.TryParse(Console.ReadLine(), out selection))
{
invalid = selection < minKms;
if (invalid)
{
Console.WriteLine("\nMinimum Kms is {0:f2} Kilometres, Please Enter a value of {0:f2} or higher", minKms);
}
}
}
return selection;
}
static double consumptionCalculation(int litres, int kms)
{
return (double)litres * 100.0 / (double)kms;
}
static void PrintResults(double consumption)
{
Console.WriteLine("\n\n\tYour Fuel Consumption is {0} Litres per 100 Kilometres", consumption);
}