C# WriteLine Works, Write fails - wacky bug? - c#

So line #59 has what i can only describe as a wackadoodle error (if i'm understanding my code correctly that is) which is that if you leave the return line with Console.ReadLine() the file will run, if you change it to Console.Read()), the file will produce errors when running. The odd thing is that it shouldn't run because I don't call the functions or do the actual console.writes, etc. So i was hoping someone out there could help me to understand this and either confirm that i am correct in thinking i've got some wacky code OR that my understanding of how the code runs is incorrect.
Code that produces the error:
public string GetStr(String StrVar)//note - using strings here
{
Console.Write(StrVar);return Console.ReadLine().ToLower().Trim();
}
If the line return Console.ReadLine() is changed to return Console.Read(), the file errors - but the file should really run regardless as i don't actually call anything - it seems like the string vars are somehow self-writing to the console if i understand what is happening.
Full Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace a015_mealCalculator
{
class Program
{
public void Play()
{
//DisplayChek("DisplayChek!");
do //do while loop
{
DisplayStr(">>>-- Meal Calculator v1.3 --<<< \n\n\n");//Welcome
//ask info
String fName = GetStr("Enter your FIRST NAME here: ");
String lName = GetStr("Enter your LAST NAME here: ");
String rName = GetStr("Enter the NAME of the RESTURANT you are dinning at here: ");
String wholeName = fName + " " + lName;
double mealCost = GetDouble("How much was your meal " + fName + "?");
String mealGreeting = "\n" + wholeName + ", your meal at " + rName + " was:";
//process math
double tax = mealCost / 8;
double tip = mealCost % 18;
double totalCost = mealCost + tip + tax;
tax = Math.Round(tax, 2);//trim decimals
tip = Math.Round(tip, 2);//trim decimals
totalCost = Math.Round(totalCost, 2);
//Announce results
Console.WriteLine("\nMeal: " + mealCost);
Console.WriteLine(mealGreeting);
Console.WriteLine("Meal: $" + mealCost);
Console.WriteLine("Tax: $" + tax);
Console.WriteLine("Tip: $" + tip);
Console.WriteLine("Total: $" + totalCost);
} while (PlayAgain());
DisplayStr("Enjoy Your Meal!"); //Salutation
}
//MaxBox
public void DisplayChek(String StringNameIs)
{ Console.WriteLine("I am in " + StringNameIs); }//Where are we?
public void DisplayStr(String StrTxt)
{ Console.WriteLine(StrTxt); }
public void DisplayRs()
{ Console.Write("\n\n"); }
public string GetStr(String StrVar)//note - using strings here
{ Console.Write(StrVar);return Console.ReadLine().ToLower().Trim(); }
public double GetDouble(String doubleRequest)// We take in a STRING but we return a DOUBLE
{
Console.WriteLine(doubleRequest + ": "); // HERE we use the STRING to ask for the DOULBE
return double.Parse(Console.ReadLine()); //HERE we RETURN the DOUBLE asked for!
}
public Boolean PlayAgain()
{
Console.Write("\n\nDo you want to play again? (y)es or (n)o: ");
String command = Console.ReadLine().ToLower();
if (command == "y" || command == "yes") return true;
return false;
}
static void Main(string[] args)
{
Program MealCalculator = new Program();
MealCalculator.Play();
//Play keeps file open
//Console.Read();
}
}
}

Console.Read() returns an integer, ReadLine() returns a string.
The ReadLine method, or the KeyAvailable property and ReadKey method are preferable to using the Read method.

If you look at the documentation of both methods: Console.Read() returns the character code of the next character read from the console stream as an integer, whilst Console.ReadLine() returns a line as a string. double.Parse accepts a string parameter, so in the first case there is a type mismatch.

This will not compile as Console.Read() returns an int. You cannot perform .ToLower() on an int.

Related

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 to delete a character from a string in console

using System;
class Strng {
// Main Method
public static void Main()
{
// define string
String str = "Some_String";
Console.WriteLine("Given String : " + str);
// delete from index 5 to end of string
Console.WriteLine("New String1 : " + str.Remove(5));
// delete character from index 8 to end of string
Console.WriteLine("New String2 : " + str.Remove(8));
}
}
The above works with the given input but I want to give input dynamically and remove a character from given string dynamically
It looks like you're wanting to read dynamically a string and a character to replace.
You can do this with the use of Console.ReadLine() or Console.ReadKey()
Implementing the following into your main method:
Console.WriteLine("Enter a string:");
string s = Console.ReadLine();
Console.WriteLine("Enter a character to remove:");
string rs = Console.ReadLine().ToString();
//Assuming if they enter 'a' you want to remove both 'a' AND 'A':
string rsUpCase = rs.ToUpper();
string rsLoCase = rs.ToLower();
s = s.Replace(rsUpCase,"");
s = s.Replace(rsLoCase,"");
Console.WriteLine(s);
//Input:
//Aardvarks are boring creatures
//Result:
//rdvrks re boring cretures
Will allow a user to enter a string dynamically (not hard-coded) and remove any character taking advantage of the Replace function - also demonstrated is the use of upper/lower case to determine if you want both variants of a character to be removed.
Hope this helps.
I think the correct question is how to read from console.
You can use Console.Read() and Console.ReadLine().
First ask for the string, and then ask for the index to remove, if this is what you mean with dynamically
This is a MSDN Example about Read
using System;
class Sample
{
public static void Main()
{
string m1 = "\nType a string of text then press Enter. " +
"Type '+' anywhere in the text to quit:\n";
string m2 = "Character '{0}' is hexadecimal 0x{1:x4}.";
string m3 = "Character is hexadecimal 0x{0:x4}.";
char ch;
int x;
//
Console.WriteLine(m1);
do
{
x = Console.Read();
try
{
ch = Convert.ToChar(x);
if (Char.IsWhiteSpace(ch))
{
Console.WriteLine(m3, x);
if (ch == 0x0a)
Console.WriteLine(m1);
}
else
Console.WriteLine(m2, ch, x);
}
catch (OverflowException e)
{
Console.WriteLine("{0} Value read = {1}.", e.Message, x);
ch = Char.MinValue;
Console.WriteLine(m1);
}
} while (ch != '+');
}
}

Input String was not in correct format || ConsoleApp

Basically I'm trying to not let the user input string instead of an integer; but on line of code:
else if (Convert.ToString(result) == "")
I get an error.
Full code:
class Program
{
static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.Red;
int calcKelvin = 273;
int calcFahren = 32;
int result = Convert.ToInt32(Console.ReadLine());
if (result == 0)
{
Console.WriteLine("Check it up on google!");
Console.Title = "I'M USELESS CONSOLE, YOU CAN NOW EXIT || I'M USELESS CONSOLE, YOU CAN NOW EXIT || I'M USELESS CONSOLE, YOU CAN NOW EXIT ||";
}
else if (Convert.ToString(result) == "")
{
Console.Write("Error, you can not convert a text");
}
else
{
Console.WriteLine("Kelvin = " + calcKelvin * result);
Console.WriteLine("Fahrenheit = " + calcFahren * result);
}
}
}
The safest way to get a number from a string is to use the TryParse method, because this method returns two values! The actual return type is a bool which indicates whether or not the string was successfully converted, and the other is an out parameter, which is of the type that we're converting to, and which gets set to the converted value (or is set to the default value of the type if the conversion fails).
For temperatures, we often deal with decimal numbers, so a double is probably a good type to store the result. So, we'll use double.TryParse.
Now, since we don't necessarily want to just quit if the user makes a mistake, we should probably do our conversion in a loop, so if it fails, we just ask the user to try again. And since this code will be used in other places as well, we can make a helper method that takes in a prompt that we display to the user, and returns the strongly-typed user response:
private static double GetDoubleFromUser(string prompt = null)
{
double result;
do
{
Console.Write(prompt);
} while (!double.TryParse(Console.ReadLine(), out result));
return result;
}
With this method, we can now just declare a double and assign it to the return value of the method above, like:
double userInput = GetDoubleFromUser("Enter a temperature: ");
Another thing we can correct in the code are the formulas used to do the conversions. A quick check online shows us that we add a number for kelvin and we do multiplication, division, and addition for Fahrenheit. We can calculate these values on the fly once we have the Celsius temperature from the user:
private static void Main()
{
double celcius = GetDoubleFromUser("Enter a Celcius temperature: ");
double fahrenheit = celcius * 9 / 5 + 32;
double kelvin = celcius + 273.15;
Console.WriteLine("Kelvin = " + kelvin);
Console.WriteLine("Fahrenheit = " + fahrenheit);
GetKeyFromUser("Done! Press any key to exit...");
}
Output
Convert.ToInt32 throws an exception if the input string is not a number. To fix that, you can use int.TryParse instead.
Example:
using System;
class Program
{
static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.Red;
int calcKelvin = 273;
int calcFahren = 32;
int result;
bool isNum=int.TryParse(Console.ReadLine(),out result);
if (!isNum)
{
Console.Write("Error, you can not convert a text");
}
else if (result == 0)
{
Console.WriteLine("Check it up on google!");
Console.Title = "I'M USELESS CONSOLE, YOU CAN NOW EXIT || I'M USELESS CONSOLE, YOU CAN NOW EXIT || I'M USELESS CONSOLE, YOU CAN NOW EXIT ||";
}
else {
Console.WriteLine("Kelvin = " + calcKelvin * result);
Console.WriteLine("Fahrenheit = " + calcFahren * result);
}
}
}

How to return a value to an array

I'm making a simple poll/survey to check where user can go to work. I went with yes or no answers. I made a point counter, so it can check user information if he answered yes then add one point. I want to make a function that displays a question and check user input instead of writing same do while loop for each question. I made an array for collecting "user points". But, the problem is that since program is jumping to loop and adding +1 point it just can't return a value to this "point array". This value is somewhere else in memory but not in array. This results to not properly working summary. It just shows everywhere 0 points to each possible work. What I've made wrong or what can I make to make it working properly?
Here's my code (I probably messed up formatting braces by copy/paste):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
namespace Survey
{
class Program
{
static void Main(string[] args)
{
//here's my Question Bank
ArrayList QuestionList = new ArrayList();
QuestionList.Add("1. Question");
QuestionList.Add("2. ...");
QuestionList.Add("3. ...");
QuestionList.Add("4. ...");
QuestionList.Add("5. ...");
QuestionList.Add("6. ...");
QuestionList.Add("7. ...");
QuestionList.Add("8. ...");
QuestionList.Add("9. ...");
QuestionList.Add("10. ...");
//here's my work list.
ArrayList WorkList = new ArrayList();
WorkList.Add("IT");
WorkList.Add("Architect");
WorkList.Add("Politician");
WorkList.Add("Driver");
WorkList.Add("Designer");
//here's an array, where I want to hold "points". The higher points the more probably user will get suggestion where to work.
int[] Work;
Work = new int[5] { 0, 0, 0, 0, 0 };
Console.WriteLine("Hi. Say 'y' if you agree or 'n' if not.");
displayQuestion(QuestionList[0], Work[0]);
displayQuestion(QuestionList[1], Work[1]);
displayQuestion(QuestionList[2], Work[2]);
displayQuestion(QuestionList[3], Work[3]);
displayQuestion(QuestionList[4], Work[4]);
displayQuestion(QuestionList[5], Work[4]);
displayQuestion(QuestionList[6], Work[1]);
displayQuestion(QuestionList[7], Work[2]);
displayQuestion(QuestionList[8], Work[0]);
displayQuestion(QuestionList[9], Work[3]);
// here's calculating maximum points
int max;
max = Work[0];
for (int i=0; i<5; i++)
{
if (Work[i] > max)
max = Work[i];
}
for (int i = 0; i < 5; i++)
{
if(Work[i]==max)
Console.WriteLine("You can work as: " + WorkList[i]);
}
//Summary
Console.WriteLine("Points as: " + WorkList[0] + " = " + Work[0]);
Console.WriteLine("Points as: " + WorkList[1] + " = " + Work[1]);
Console.WriteLine("Points as: " + WorkList[2] + " = " + Work[2]);
Console.WriteLine("Points as: " + WorkList[3] + " = " + Work[3]);
Console.WriteLine("Points as: " + WorkList[4] + " = " + Work[4]);
Console.ReadLine();
}
//here's the PROBLEM (I think)
public static int displayQuestion(object whichQuestion, int WorkPoints)
{
string answer;
do
{
Console.WriteLine(whichQuestion);
answer = Console.ReadLine();
if (answer == "y")
{
WorkPoints++;
}
} while (answer != "y" && answer != "y");
return WorkPoints;
}
}
}
actually you're assigning the new score to the return value of the displayQuestion Method and not using it.
public static int displayQuestion(object whichQuestion, int WorkPoints)
so a possible approach is tu use the ref keyword as Samvel said or assign the return value of the method to work[i]:
Work[0] = displayQuestion(QuestionList[0], Work[0]);
Change the function to the following:
public static int displayQuestion(object whichQuestion)
{
string answer;
int WorkPoints = 0;
do
{
Console.WriteLine(whichQuestion);
answer = Console.ReadLine();
if (answer == "y")
{
WorkPoints++;
}
} while (answer != "y" && answer != "n");
return WorkPoints;
}
}
and then use it this way:
Work[0] += displayQuestion(QuestionList[0]);

C# code issue - Code not working properly

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.

Categories

Resources