When Input Values To My Program, It Crashes :( C# [duplicate] - c#

This question already has answers here:
What's the main difference between int.Parse() and Convert.ToInt32
(13 answers)
Closed 4 years ago.
This is the program. Can someone tell me what I did wrong? Every time I input a value for the string SolvingFor, the program crashes. I'm new to coding so if I made a stupid mistake please tell me.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PercentageCalculator
{
class Program
{
static void Main(string[] args)
{
string SolvingFor;
int part;
int whole;
int percent;
Console.WriteLine("please only use numbers and lowercase letters.");
Console.WriteLine("Are you trying to solve for percent, part, or whole?");
SolvingFor = Convert.ToString(Console.Read());
if (SolvingFor == "part") {
Console.WriteLine("Please Enter Value of the Whole");
whole = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please Enter Value of the Percent");
percent = Convert.ToInt32(Console.ReadLine()); ;
Console.WriteLine("Your answer is" + (whole * percent) / 100); }
else if (SolvingFor == "whole")
{
Console.WriteLine("Please Enter Value of the part");
part = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please Enter Value of the Percent");
percent = Convert.ToInt32(Console.ReadLine()); ;
Console.WriteLine("Your answer is" + (part * 100) / percent);
}
else if (SolvingFor == "percent")
{
Console.WriteLine("Please Enter Value of the part");
part = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please Enter Value of the whole");
whole = Convert.ToInt32(Console.ReadLine()); ;
Console.WriteLine("Your answer is" + (part * 100) / whole);
}
else
{
Console.WriteLine("Please only input valid lowercase letters and numbers. ");
};
Console.Read();
}
}
}

//SolvingFor = Convert.ToString(Console.Read());
SolvingFor = Convert.ToString(Console.ReadLine());
if you put(hover) the mouse over ReadLine
you will see that it returns a string so Convert.ToString is not needed
SolvingFor = Console.ReadLine();

First Issue:
Below line from your code is reading just one character.
Instead of Console.Read(), use Console.ReadLine() to enable you to input multiple characters.
SolvingFor = Convert.ToString(Console.Read());
Second Issue:
You are using Convert.ToInt32(Console.Readline());
Please note that Convert.ToInt32 will throw an exception in anything apart from number is provided as input.
Better use int.TryParse which returns if the conversion is successful or not.

Related

I can't get any output and my statements don't execute properly because of this, however, every if statement does execute even when it shouldn't? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I want to write a program that multiples four numbers and outputs their sign whether if the answer is a negative or a positive number. I had to write the program using a logical operator but the thing is that I wanted to try first using a simple if statement series while also using relational operators. I wrote this code, and checked it multiple times, the code compiles and executes but shows no output. It says "The answer is " followed by a blank space and shows all 3 of my if statements. Can someone please kindly fix my code for me (and possibly tell me how to write such a program using logical operators where I give 4 inputs and I get the output saying if the answer after multiplying the 4 numbers is positive or negative, and if is there any way to do that without actually calculating aka multiplying) and tell me what exactly is wrong with my code. The code is given here:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Program746
{
class Program
{
static void Main(string[] args)
{
int a, b, c, d;
Console.WriteLine("Please enter the first number:");
a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please enter the second number:");
b = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please enter the third number:");
c = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please enter the fourth number:");
d = Convert.ToInt32(Console.ReadLine());
int e = a * b * c * d;
if (e < 0) ;
{
Console.WriteLine("The result is negative and has the '-' sign ");
}
if (e > 0) ;
{
Console.WriteLine("The result is positive and has the'+' sign");
}
if (e == 0) ;
{
Console.WriteLine("The result is zero, and does not have a sign");
}
Console.WriteLine("The answer is ", e);
Console.ReadKey();
}
}
}
static void Main(string[] args)
{
int a, b, c, d;
Console.WriteLine("Please enter the first number:");
a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please enter the second number:");
b = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please enter the third number:");
c = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please enter the fourth number:");
d = Convert.ToInt32(Console.ReadLine());
int e = a * b * c * d;
if (e < 0)
{
Console.WriteLine("The result is negative and has the '-' sign ");
}
if (e > 0)
{
Console.WriteLine("The result is positive and has the'+' sign");
}
if (e == 0)
{
Console.WriteLine("The result is zero, and does not have a sign");
}
Console.WriteLine("The answer is {0}", e);
Console.ReadKey();
}
Delete the semicolon after each if statement. Because with a semicolon at the end you terminate the if.
You can check out this link: https://social.msdn.microsoft.com/Forums/en-US/3508c3a2-fd1c-49db-93ea-f7bb5c2d27f4/extra-semicolon-suberst-conditional-flow?forum=csharpgeneral
Your if:
if (e < 0) ;
{
...
}
Correct if:
if (e < 0)
{
...
}
Instead of using four ReadLines, you could do a for loop with i = 4 and multiply each number to a result int or save them in a int array.
I would write the program like this:
static void Main(string[] args)
{
int result = PrintSign(4);
Console.WriteLine(string.Format("The answer is {0}", result));
Console.ReadLine();
}
private static int PrintSign(int maxNumbers)
{
int result = 0;
for (int i = 0; i < maxNumbers; i++)
{
int number = 0;
while (true)
{
Console.WriteLine(string.Format("Please enter number {0}:", i));
if (int.TryParse(Console.ReadLine(), out number))
break;
}
// if one number is zero, return 0 (multiply with zero and it's zero all the time)
if (number == 0)
return 0;
result *= number;
}
// check for negative number
if (result < 0)
Console.WriteLine("The result is negative and has the '-' sign");
// else, because zero is not possible at this point
else
Console.WriteLine("The result is positive and has the'+' sign");
return result;
}
Please like and accept the answer if this answered your question :)

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.

How to check if entered input has exactly 10 characters using arrays?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace sample
{
class Program
{
static void Main(string[] args)
{
int[] studentNumber = new int[10];
string firstname, lastname;
int i, unit;
double grade, gwa;
Console.Write("enter first name: ");
firstname = Console.ReadLine();
Console.Write("enter last name: ");
lastname = Console.ReadLine();
Console.Write("enter student number: ");
if (studentNumber.Length != 10)
{
Console.Write("student number must be 10 characters!");
Console.ReadLine();
}
MessageBox.Show(firstname + " " + lastname + "\n" + studentNumber, "Mapua");
}
}
}
How can I check if the user entered exactly 10 characters? And if the user did, how would I call that to my message box method? How could I show that in the output? Thank you!
You can just check with,
if(studentNumber.Length != 10)
{
Console.Write("Student number must be 10 characters");
}
And you cannot use messageBox in a console application, change it to windows form.
Here's one way to get the student number from the user, forcing them to enter 10 digits, and adding each valid character to your studentNumber array. The code basically does this:
Prompt the user to input the student number
While they have input less than 10 numbers:
Read the next key entered by the user
If the key entered is not a number (which we can determine by ensuring that the character is not less than 0 or greater than 9), then subtract one from the cursor postion (making them re-enter the number), write a blank space over their entry, and back up the cursor position again (so it looks like their input was rejected, which it was).
If the key is a number, add it to our array and increment a counter so we know when they've entered 10 numbers:
Here's the sample code:
int[]studentNumber = new int[10];
Console.Write("enter student number: ");
int numbersEntered = 0;
while (numbersEntered < 10)
{
var input = Console.ReadKey();
// If the input is not a number, then reject their input by
// backing up one character, writing a blank space over their
// entry, and then back up again so we can get the next key.
if (input.KeyChar < '0' || input.KeyChar > '9')
{
Console.CursorLeft -= 1;
Console.Write(" ");
Console.CursorLeft -= 1;
continue;
}
studentNumber[numbersEntered] = int.Parse(input.KeyChar.ToString());
numbersEntered++;
}
At the end of this loop, the studentNumber array will contain the 10 numbers entered by the user.

How to make C# check for which numbers are entered by the user?

I'm making a where the users enters as many numbers as they want,so long as they're between 1 and 10, then once they're done the program lists the number they entered and how many times. Like this
Now my question is how would you make C# read and check which numbers they entered and print them out and how many times they entered it like in the bottom of the picture? Sorry for the noob question i'm new to this language.
Here is what I have so far:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Assignment_3
{
class Program
{
static void Exercise1()
{
//int min;
//int max;
//Console.WriteLine("Enter minimum integer: ");
//min = int.Parse(Console.ReadLine());
//Console.WriteLine("Enter maximum integer: ");
//max = int.Parse(Console.ReadLine());
//int start = min;
}
static void Exercise2()
{
string entry;
Console.Write("Enter an integer or 'q' to quit ");
entry = Console.ReadLine();
while (entry.ToLower() != "q")
{
int number;
if (int.TryParse(entry, out number))
{
if (number >= 1 && number <= 10)
{
}
else
{
Console.WriteLine("Your number must be between 1 and 10");
}
}
Console.Write("Enter an integer or 'q' to quit ");
entry = Console.ReadLine();
}
}
static void Main(string[] args)
{
Exercise1();
Exercise2();
Console.WriteLine("Press enter to end");
Console.ReadLine();
}
}
}
Well, we do not do your homework, so I will just point you around in the documentation with enough information you are not lost.
Use a Dictionary to keep the nnumber and counter. This is easiest - if a number is entered, get the counter, add one, put back into dictionary. If not - set 1 as value for the number.
At the end you go throuch all the keys (that are the numbers) and print the corresponding values (the number of times).

C# FormatException error [duplicate]

I keep getting a FormatException in each of the cases on the line where I try to assign the value for the sale variable. Anyone know what I am doing wrong? I am supposed to make this console program as homework to learn about loops, but I am finding out more about other things. It is supposed to keep a running tab of salesperson's commission based a a 10% commission of each sale. Anyways, here is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TubSales
{
class Program
{
static void Main(string[] args)
{
char initial;
const double COMM_INT = 0.10;
double sale, aComm = 0, bComm = 0, eComm = 0;
Console.Write("Enter 'A' for Andrea, 'B' for Brittany,\n'E' for Eric, or 'Z' to quit >> ");
initial = Convert.ToChar(Console.Read());
while (initial != 'z' && initial != 'Z')
{
switch (initial)
{
case 'a':
case 'A':
Console.Write("Enter the sales for Andrea >> ");
sale = Convert.ToDouble(Console.ReadLine());
aComm = aComm + COMM_INT * sale;
break;
case 'b':
case 'B':
Console.Write("Enter the sales for Brittany >> ");
sale = Convert.ToDouble(Console.ReadLine());
bComm = bComm + COMM_INT * sale;
break;
case 'e':
case 'E':
Console.Write("Enter the sales for Eric >> ");
sale = Convert.ToDouble(Console.ReadLine());
eComm = eComm + COMM_INT * sale;
break;
default:
Console.WriteLine("You did not enter a valid initial");
break;
}
Console.Write("Enter 'A' for Andrea, 'B' for Brittany, or 'E' for Eric >> ");
initial = (char)Console.Read();
}
Console.WriteLine("Andrea had {0}, Brittany had {1}, and Eric had {2} in commissions.", aComm.ToString("C"), bComm.ToString("C"), eComm.ToString("C"));
Console.Write("Press any key to exit... ");
Console.ReadKey();
}
}
}
I keep getting a FormatException in each of the cases on the line where I try to assign the value for the sale variable. Anyone know what I am doing wrong?
The Convert.ToDouble method will raise a FormatException if the string (returned from Console.ReadLine()) is not a valid number.
Typically, if you want to parse user input, it's a better idea to use Double.TryParse instead, as this lets you determine whether the input was a valid number without catching the exception.
This would normally look something like:
Console.Write("Enter the sales for Andrea >> ");
while (!double.TryParse(Console.ReadLine(), out sale))
{
Console.WriteLine("Value entered was not a valid number.");
Console.Write("Enter the sales for Andrea >> ");
}
// Once you get here, "sale" will be set appropriately
While Reed's answers is great, it's not the problem here.
What really happens is the same situation as this one
Console.Read only read the "Second part of the carriage return" and returns "". This is why the Convert fails.
replace
initial = Convert.ToChar(Console.Read());
with
initial = Convert.ToChar(Console.ReadLine());
Replace
initial = Convert.ToChar(Console.Read());
with
initial = Convert.ToChar(Console.ReadLine().FirstOrDefault());

Categories