Temperature converter - c#

Im am trying to solve an issue.
My teacher wants us to do a C# console with temperature converter from Celsius to Fahrenheit and switch. The problem is I continue getting errors in my coding and I don't know where I started wrong in order to get completely lost. Just to mention I am in the beginning and I would appreciate some help.
We should write a program that displays a list of temperatures in Celsius converted to Fahrenheit and vice versa. A menu is provided for the user to choose the type of conversions: The menu should repeat until the user chooses 0 to exit.
When option 1 is chosen, the program calculates and displays a list of values between 0 and 212 degrees in Fahrenheit converted to Celsius degrees as shown in the next image When option 2 is selected, the program lists values from 0 to 100 Celsius converted to Fahrenheit degrees.
This is my beginning:
using System;
namespace TempconverterA2
{
class TemperatureConverter
{
public void Start()
{
Console.WriteLine("**************************************");
Console.WriteLine("\t MAIN MENU");
Console.WriteLine("**************************************");
Console.WriteLine(" Convert Fahrenheit to Celsius : 1");
Console.WriteLine(" Convert Celsius to Farenheit : 2");
Console.WriteLine(" Exit the Converter : 0");
Console.WriteLine("**************************************");
Console.WriteLine("\nYour choice: ");
switch (choice)
{
case 1:
CalculateFarenheitToCelsius(F = 9 / 5 * C + 32);
break;
case 2:
CalculateCelsiusToFarenhet(C = 5 / 9 * (F - 32));
case 0: //do nothing (exists to loop)
break;
default:
Console.WriteLine("Invalid option. Choose between 0 and 2.");
break;
} while (choice != 0) ;
public void CalculateCelsiusToFarenhet()
{
double convertedValue = 0;
stringtextOut = string.Empty;
for (int i= 0, i <= 100; i += 5)
{
convertedValue = CalculateCelsiusToFarenhet(i);
textOut = string.Format("{0,16:f2} C = {1,6:f2} F", i, convertedValue);
Console.WriteLine(textOut);
}
Console.WriteLine();
}
}//End of Start

This is not doing what you think it is:
switch (choice)
{
// case statements removed for brevity
} while (choice != 0);
It is actually doing this:
switch (choice)
{
}
while (choice != 0)
{
// infinite loop if choice != 0
}
This is because switch is a control block and while is a separate control block.

Related

How to allow user to input new values in an if statement

I would like for someone to help me by telling me what code I should use in case the input number turns out to be for the second if or third if, if the user doesn't put the right amount (73-77) then id like the user to be able to type in a new value I can use... how do I do that please?
namespace test
{
class Program
{
public static int FahrToCels(int fahr)
{
int cel = (fahr - 32) * 5 / 9;
return cel;
}
static void Main(string[] args)
{
Console.WriteLine("write down temprature: ");
int fahrenheit = int.Parse(Console.ReadLine());
int celsius = FahrToCels(fahrenheit);
Console.Write("Press any key to continue . . .");
Console.ReadKey(true);
do
if (celsius >= 73 && celsius <= 77)
{
Console.WriteLine("now it works ");
}
else if (celsius < 72)
{
Console.WriteLine("");
}
else if (celsius > 77)
{
Console.WriteLine("");
}
while (true);
}
}
}
There are a few major issues with what you have. Attached is working code for what I believe you are looking for, though in your ifs you have Celsius range in the 70s when the point of your Fahrenheit to Celsius converter turns the value into Celsius which would lie in the 20s range.
namespace test
{
class Program
{
public static int FahrToCels(int fahr)
{
int cel = (fahr - 32) * 5 / 9;
return cel;
}
static void Main(string[] args)
{
int celsius;
int fahrenheit;
do
{
Console.WriteLine("Skrive in Temperaturen: ");
fahrenheit = int.Parse(Console.ReadLine());
celsius = FahrToCels(fahrenheit);
Console.Write("Presifs any key to continue . . .");
Console.ReadKey(true);
if (celsius >= 22 && celsius <= 28)
{
Console.WriteLine("now it works ");
//Insert whatever here
break;
}
else if (celsius < 22)
{
//Something to tell them they need to retry
}
else if (celsius > 28)
{
//Something to tell them they need to retry
}
}
while (celsius >= 22 && celsius <= 28);
}
}
}
I would recommend changing the range on your ifs to the values you want the user to input, and also provide the user with some error/retry statement in your elseifs. Also would recommend instead of having two elseifs just use else. Also would remove that stupid readkey() in my opinion.
If you have any questions to my answer leave them in the comments.
If you want to ensure that celsius is in [73..77] range you can try
static void Main(string[] args) {
int fahrenheit;
int celsius;
// Keep asking user until (s)he enters a valid celsius value
while (true) {
Console.WriteLine("Skrive in Temperaturen: ");
// check if value a valid integer, and not say "bla-bla-bla"
if (!int.TryParse(Console.ReadLine(), out fahrenheit)) {
Console.WriteLine("Not an integer value, please, try again");
continue;
}
// fahrenheit is a valid integer value, we can compute corresponding celsius...
celsius = FahrToCels(fahrenheit);
// ... and validate the celsius value then
if (celsius < 73)
Console.WriteLine("Too low temperature (below 73 degree Celsius)");
else if (celsius > 77)
Console.WriteLine("Too high temperature (above 77 degree Celsius)");
else
break; // celsius is valid integer value in [73..77] range
}
// From now on celsius contains integer in [73..77] range
Console.WriteLine("Now it works");
Console.Write("Press any key to continue . . .");
Console.ReadKey(true);
}

How to press enter for a menu without the enter being used for the next operation

So, I am learning C#, and to practice, I have been trying to make a math solver, so the way I did it, is 1- I present the math question, 2- I receive user-input of the solution, 3- I compare the user's answer to my answer using an if statement, now, I am trying to add a console menu to add different divisions (multiplication/division/sub./add.), i have successfully added the menu, however I am not able to move onto inputting the numbers, the error I get is http://prntscr.com/ohru2i, how can I fix it?
I have tried putting Console.clear(), I have also tried to use break;, but none of them worked
using Figgle;
using System;
using System.Threading;
public class MainClass
{
public static void Main()
{
Console.Title = $"The Math Solver | Correct = 0 | Wrong = 0";
char choice;
for (; ; )
{
do
{
Console.WriteLine("Choose Method:");
Console.WriteLine(" 1. Multiplication");
Console.WriteLine(" 2. Division");
Console.WriteLine(" 3. Addition");
Console.WriteLine(" 4. Subtraction");
Console.WriteLine(" 5. Find the Remainder");
Console.WriteLine("Press Q to Exit ");
do
{
choice = (char)Console.Read();
} while (choice == '\n' | choice == '\r');
} while (choice < '1' | choice > '5' & choice != 'q');
if (choice == 'q') break;
Console.WriteLine("\n");
Console.Clear();
switch (choice)
{
case '1':
{
Console.WriteLine(
FiggleFonts.Standard.Render("Multiplication"));
int milliseconds2 = 2000;
Thread.Sleep(milliseconds2);
int correctAnswers = 0;
int WrongAnswers = 0;
int Number1;
int Number2;
int myInt2;
while (true)
{
Console.WriteLine("Write the first number to multiply");
Number1 = int.Parse(Console.ReadLine());
Console.WriteLine("Write the second number to multiply");
Number2 = int.Parse(Console.ReadLine());
Console.WriteLine($"Write the answer of {Number1} * {Number2}");
myInt2 = int.Parse(Console.ReadLine());
if (myInt2 == Number1 * Number2)
{
Console.WriteLine(
FiggleFonts.Standard.Render("Correct!"));
correctAnswers++;
Console.Title = $"The Math Solver | Correct = {correctAnswers} | Wrong = {WrongAnswers}";
}
else
{
Console.WriteLine(
FiggleFonts.Standard.Render("Wrong"));
WrongAnswers++;
Console.Title = $"The Math Solver | Correct = {correctAnswers} | Wrong = {WrongAnswers}";
}
int milliseconds3 = 2000;
Thread.Sleep(milliseconds3);
Console.Clear();
}
}
}
}
}
The error message I get is http://prntscr.com/ohru2i
You're getting the error when converting a number to a string because console.Read() consumes the first character from the standard input, but leaves the line break from the user hitting enter. Therefore, the next time you go to read a line from the console, you just get a blank line, which is not a valid string for number conversion.
Solution is to use Console.ReadLine() and either look at the first character by indexing the string, or replace choice character constants with string constants.

Return to a specific block of code in my application

I am fairly new to C# and currently building a simple ATM app. I am attempting to write code to return the user to the main menu according to his/her entry of the letter M. The break, continue, goto or return keywords do not seem to work in my scenario; perhaps I used them incorrectly. The statement directly below is where I would like to jump to.
Console.WriteLine("Select an option? \n VIEW BALANCE (B1) checking, (B2) saving \n DEPOSIT (C1) checking, (C2) saving \n WITHDRAW (W1) checking, (W2) saving");
I would like to jump from the line JUMP (below) within the else if statement nested within the switch statement into the section of code above. How can I achieve this? any help is appreciated...thanks!
switch (response)
{
case "C1":
Console.WriteLine("How much would you like to deposit to your checking account?");
string depositEntry = Console.ReadLine();
double checkingBalance = Convert.ToInt32(depositEntry) + currentCheckingBalance;
currentCheckingBalance += checkingBalance;
Console.WriteLine("Your current checking balance is " + checkingBalance + "\n (X) Exit, (M) Main Menu" );
string selection = Console.ReadLine().ToUpper();
if (selection == "X")
{
return;
}
else if (selection == "M")
{
***JUMP***
}
else
{
Console.WriteLine("Your entry was invalid");
}
break;
case "C2":
break;
case "W1":
Using a jump statement usually indicates the flow of logic is jumbled. I try to avoid any kind of jumps if necessary. The code below prints out a main menu and if the user types “x” the program will quit. If the user selects one of the other options, a message is simply printed out indicating what the user selected. After the user presses any key, the console clears and the main menu is re-displayed.
In the main menu, if the user does not type one of the selections, then the selection is ignored, the console is cleared, and the menu is reprinted. No error is displayed indicating invalid selections.
This does not require the user to type “m” to go back to the main menu. After a selection is made for Deposit/withdraw/… after the method is finished the code will automatically return to the main menu.
I am guessing this may be what you are looking for. Hope this helps.
static void Main(string[] args) {
string userInput = "";
while ((userInput = GetMainSelection()) != "x") {
switch (userInput) {
case "c1":
Console.WriteLine("C1 Deposit Checking method");
break;
case "c2":
Console.WriteLine("C2 Deposit Savings method");
break;
case "b1":
Console.WriteLine("B1 View Balance Checking method");
break;
case "b2":
Console.WriteLine("B2 View Balance Savings method");
break;
case "w1":
Console.WriteLine("W1 Withdraw Checking method");
break;
case "w2":
Console.WriteLine("W2 withdraw Savings method");
break;
}
Console.WriteLine("Press Any Key to continue"); // <-- show what method was just used
Console.ReadKey();
Console.Clear();
}
Console.Write("Press any key to exit the program");
Console.ReadKey();
}
private static string GetMainSelection() {
string userInput = "";
while (true) {
Console.WriteLine("Select an option? \n VIEW BALANCE (B1) checking, (B2) saving \n DEPOSIT (C1) checking, (C2) saving \n WITHDRAW (W1) checking, (W2) saving. (X) to EXit");
userInput = Console.ReadLine().ToLower();
if (userInput == "b1" || userInput == "b2" || userInput == "c1" || userInput == "c2" || userInput == "w1" || userInput == "w2" || userInput == "x") {
return userInput;
}
else {
Console.Clear();
}
}
}
Put the JUMP code in a function and return.
public void MainMenu() {
// Show the main menu
}
public void Response(string response) {
switch (response)
{
case "C1":
Console.WriteLine("How much would you like to deposit to your checking account?");
string depositEntry = Console.ReadLine();
double checkingBalance = Convert.ToInt32(depositEntry) + currentCheckingBalance;
currentCheckingBalance += checkingBalance;
Console.WriteLine("Your current checking balance is " + checkingBalance + "\n (X) Exit, (M) Main Menu" );
string selection = Console.ReadLine().ToUpper();
if (selection == "X")
{
return;
}
else if (selection == "M")
{
***JUMP***
MainMenu();
return;
}
else
{
Console.WriteLine("Your entry was invalid");
}
break;
case "C2":
break;
case "W1":
}
}
Similar to the already given answer, I suggest breaking this out. Here's an example:
The Main method:
static void Main(string[] args) {
string input = null;
do {
input = Console.ReadLine();
ParseInput(input);
} while (input != "X");
}
ParseInput:
static void ParseInput(string input) {
switch (input) {
case "X": //from Main(), this will close the app
return;
case "M":
MainMenu();
break;
case "C1":
ShowAccount("C1"); //move your deposit/withdraw logic into a method and call with the selected account
return;
//other accounts
default:
break; //error message?
}
}
and MainMenu:
static void MainMenu() {
Console.WriteLine("Select an option? \n VIEW BALANCE (B1) checking, (B2) saving \n DEPOSIT (C1) checking, (C2) saving \n WITHDRAW (W1) checking, (W2) saving");
}
This should let you read the input in a loop and the ParseInput function can handle your individual cases. You may also want to call MainMenu() at the start, so it shows from the beginning.
It works like this:
Get input from the user
Pass the input to ParseInput() which decides where to go next.
Any functions hit in ParseInput() will execute, writing to the console or asking for further input
Once that function returns, while (input != "X") evaluates. If input != "X", goto 1, else exit.
I suggest you use goto C# reference.
static void Main()
{
int x = 200, y = 4;
int count = 0;
string[,] array = new string[x, y];
// Initialize the array:
for (int i = 0; i < x; i++)
for (int j = 0; j < y; j++)
array[i, j] = (++count).ToString();
// Read input:
Console.Write("Enter the number to search for: ");
// Input a string:
string myNumber = Console.ReadLine();
// Search:
for (int i = 0; i < x; i++)
{
for (int j = 0; j < y; j++)
{
if (array[i, j].Equals(myNumber))
{
goto Found;
}
}
}
Console.WriteLine("The number {0} was not found.", myNumber);
goto Finish;
Found:
Console.WriteLine("The number {0} is found.", myNumber);
Finish:
Console.WriteLine("End of search.");
// Keep the console open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
Output for the Input 44 would be:
Enter the number to search for: 44
The number 44 is found.
End of search.
See here for the MSDN reference.

Getting Values from User

hello please i am having issues getting the values of a system generated variables. here is the code for the getting the values from user;
public void DetailsRate()
{
begin1:
Console.WriteLine("\n \t Rate the Acting on a scale of 0 to 5");
RateActing = int.Parse(Console.ReadLine());
switch (RateActing)
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
Console.WriteLine("\n you have rated the action of the movie {0}", RateActing);
break;
default:
Console.WriteLine("you have selected the wrong choice {0}", RateActing);
goto begin1;
}
begin2:
Console.WriteLine("\n \t Rate the music of the movie on a scale of 0 to 5");
RateMusic = int.Parse(Console.ReadLine());
switch (RateMusic)
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
Console.WriteLine("you have rated the music of the movie {0}", RateMusic);
break;
default:
Console.WriteLine("you have selected the wrong choice {0}", RateMusic);
goto begin2;
}
}
I called the inputed values into this piece of code
public double getoverallRate(double rateact, double ratemus)
{
double totrate = 0;
rateact = RateActing * 0.25;
ratemus = RateMusic * 0.15;
totrate = (rateact + ratemus);
return totrate;
}
and here is the main method
static void Main(string[] args)
{
MovieRating MR = new MovieRating();
MR.DetailsRate();
MovieRating MT = new MovieRating();
double totrate = MT.getoverallRate(1, 2);
Console.WriteLine("total rate is {0}", totrate);
Console.ReadKey();
}
Please what Im i missing the value of totrate is just giving me 0. please help me.
First get rid of the goto statements. At a quick glance you could write this:
static void Main(string[] args)
{
double RateActing = -1;
double RateMusic = -1;
RateActing = GetMovieRating(RateActing);
RateMusic = GetMovieMusicRating(RateMusic);
double totrate = getoverallRate(RateActing, RateMusic);
Console.WriteLine("total rate is {0}", totrate);
Console.ReadKey();
}
private static double GetMovieRating(double RateActing)
{
do
{
Console.WriteLine("\n \t Rate the Acting on a scale of 0 to 5");
double.TryParse(Console.ReadLine(), out RateActing);
}
while (RateActing < 0 || RateActing > 5);
Console.WriteLine("\n you have rated the action of the movie {0}", RateActing);
return RateActing;
}
private static double GetMovieMusicRating(double RateMusic)
{
do
{
Console.WriteLine("\n \t Rate the music of the movie on a scale of 0 to 5");
double.TryParse(Console.ReadLine(), out RateMusic);
}
while (RateMusic < 0 || RateMusic > 5);
Console.WriteLine("\n you have rated the music of the movie {0}", RateMusic);
return RateMusic;
}
public static double getoverallRate(double rateact, double ratemus)
{
rateact *= 0.25;
ratemus *= 0.15;
return rateact + ratemus;
}
There are lots of problems here - almost enough to start over!
First: Never use goto - there are better ways to construct your program flow.
Second: Your method getoverallRate takes less parameters (2) than what you're passing in (5) so this shouldn't even build.
Third: You are referencing three additional variables in getoverallRate that look like they should be local variables but they are not defined anywhere. Should these be passed in like the usage implies in Main.
Fourth: you are passing in values in variables rateact and ratemus but you are overwriting them immediately with your calculations.
Fifth: It would make more sense to me if you were passing in the input values from the user to this method along with any others you need. You should not be using Global variables from user input in any method that calculates values and returns a result. You should always pass in whatever is needed by the calculation.
Sixth: What is the point of the MR declaration and what does DetailsRate do?

c# random operators and math problems, do loop

Hey guys im trying to work on this assignment i have. I am new to programming and this is my third assignment. Any help would be appreciated. Im not sure if im on the right track or not. here is what i have to do:
allow the user to enter a numeric answer to math problem and display their average score. The user will be allowed to answer as many math problems as they choose. After each entry we will display the current average score. The difference between the while loop and the do loop is the while loop tests a condition before running its code block where the do loop will execute its code block and then test a condition. Hence the names of pre-test loop for the while loop and post-test loop for the do loop. Since the do loop is a post-test loop, it will always execute its code block one time at a bare minimum.
these are the steps im trying to follow:
Inside the Main method block of code we are going to create a do loop. The advantage of a do loop is that it will always execute one time. In this application we will use that advantage to repeat several steps. The following steps are what we want to repeat:
Clear the console Display window. (This will keep the display from getting cluttered)
Use random object to get/store two random numbers for a math problem.
Randomly decide which math operator to use (+-*/)and store the symbol.
Display an application header and the math problem formatted.
Get the answer from the user and store it in a variable(i.e.“input”).
Convert variable(input)from a string to a double or integer.
Based on the math symbol calculate the correct answer using random numbers.
If user entry matches correct answer,add question point value to points earned total.
Add the question point value to the points possible total.
Display message with points earned, possible, and the average (earned/possible).
Display a message asking the user if they want to quit or get a new math problem.
Pause display and get the user response of quit or continue.!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MathProblems
{
class Program
{
static void Main(string[] args)
{
string input;
double totalPoints = 0;
double userEarnedPoints = 0;
double average = 0;
int number1 = 0;
int number2 = 0;
int operators = 0;
int answer = 0;
double correctAnswer = 0;
int mathProblem = 0;
do
{
Console.Clear();
Random number = new Random();
number1 = number.Next(1, 31);
number2 = number.Next(1, 31);
operators = number.Next(1, 5); // 1 = add, 2 = minus, 3 = multiply, 4 = divide
Console.WriteLine("\tMath Problems\n");
switch (operators)
{
case 1:
answer = number1 + number2;
break;
case 2:
answer = number1 - number2;
break;
case 3:
answer = number1 * number2;
break;
case 4:
answer = number1 / number2;
break;
default:
break;
}
//if (operators == 1)
//{
// Console.WriteLine("{0} + {1} = ", number1, number2);
//}
//else if (operators == 2)
//{
// Console.WriteLine("{0} - {1} = ", number1, number2);
//}
//else if (operators == 3)
//{
// Console.WriteLine("{0} * {1} = ", number1, number2);
//}
//else if (operators == 4)
//{
// Console.WriteLine("{0} / {1} = ", number1, number2);
//}
//break;
} while (true);
Console.ReadLine();
In order to get user input, you need to do Console.ReadKey() (for a single character) or Console.ReadLine() (for a string of characters terminated by Enter). You can then capture this input in a variable and then do a comparison on it to get the user's answer or to determine if they want to continue or not.
You also will need to validate that the input was an integer. You can use int.TryParse() to do this. It will return true if the string was an integer, and will store the integer in the out parameter.
You can then compare the userAnswer to the actual answer to see if they got it right. It also looks like you need to increment the total problems and the user score (when they get an answer correct)
One way to do this would be:
{
var rnd = new Random();
var quit = false;
var userScore = 0;
var totalProblems = 0;
var percentCorrect = 0d;
while (!quit)
{
Console.Clear();
var number1 = rnd.Next(1, 31);
var number2 = rnd.Next(1, 31);
var operation = rnd.Next(1, 5);
string operatorString;
int answer;
totalProblems++;
Console.WriteLine("\tMath Problem:");
Console.WriteLine("\t-------------");
switch (operation)
{
case 1:
answer = number1 + number2;
operatorString = "+";
break;
case 2:
answer = number1 - number2;
operatorString = "-";
break;
case 3:
answer = number1 * number2;
operatorString = "*";
break;
case 4:
answer = number1 / number2;
operatorString = "/";
break;
default:
answer = 0;
operatorString = "?";
break;
}
Console.WriteLine("\t{0} {1} {2}", number1, operatorString, number2);
Console.Write("\nEnter your answer here (round down if necessary): ");
var input = Console.ReadLine();
int inputAsInt;
while (!int.TryParse(input, out inputAsInt))
{
Console.Write("Answer must be an integer. Try again: ");
input = Console.ReadLine();
}
if (inputAsInt == answer)
{
Console.WriteLine("Correct!");
userScore++;
}
else
{
Console.WriteLine("Sorry, the correct answer was: {0}", answer);
}
percentCorrect = Math.Round((double)userScore / totalProblems * 100, 2);
Console.WriteLine("\nYou have answered {0} of {1} questions correctly, " +
"for a total of {2}%.", userScore, totalProblems, percentCorrect);
Console.Write("\nPress 'q' to quit, or any other key to continue... ");
if (Console.ReadKey().Key == ConsoleKey.Q) quit = true;
}
var letterGrade =
percentCorrect < 60 ? "F"
: percentCorrect < 67 ? "D"
: percentCorrect < 70 ? "D+"
: percentCorrect < 73 ? "C-"
: percentCorrect < 77 ? "C"
: percentCorrect < 80 ? "C+"
: percentCorrect < 83 ? "B-"
: percentCorrect < 87 ? "B"
: percentCorrect < 90 ? "B+"
: percentCorrect < 93 ? "A-"
: "A";
Console.WriteLine("\n\nThank you for playing. You've earned you a letter " +
"grade of: {0}", letterGrade);
Console.Write("\nPress any key to exit...");
Console.ReadKey();
}

Categories