Make Exceptions work [closed] - c#

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 8 years ago.
Improve this question
I am not sure how to get the exceptions to work
the program should prompt for the whole number of pounds to convert and the exchange rate. It then should display the equvlient number of follars in a manner similar to the output below.
the first part works here is my code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CurrencyConvertor
{
class Program
{
static void Main(string[] args)
{
CurrencyConvertor();
Console.ReadLine();
}
private static void CurrencyConvertor()
{
int ivalue;
float exchange;
float results;
bool valid;
Console.WriteLine(" please enter a whole number of pounds");
do
{
try
{
ivalue = int.Parse(Console.ReadLine());
Console.WriteLine(" pounds entered : " + ivalue);
Console.WriteLine("please enter the exchange rate");
exchange = float.Parse(Console.ReadLine());
Console.WriteLine(" exchange rate is " + exchange);
results = ivalue * exchange;
Console.WriteLine(" £ " + ivalue + " is equivlent to" + " $ {0:N}", results);
valid = true;
}
catch
{
Console.WriteLine("unable to convert to integer");
Console.WriteLine(" Try again- ensure you enter a number");
valid = false;
}
} while (valid == false);
Console.ReadLine();
}
}
}
Both inputs should be validated to ensure that the user enters an appropriate data type - the output below illustrates the expected output if the user enters non numerical data.
so it should displays
please enter an integer
try again - ensure you enter an integer
12
pounds entered 12
please enter an exchange rate
asd
unable to convert to a number
try again - ensure you enter a number
1.56
exchange rate is 1:56
£12.00 is equivalent to $18.72
I cant seem to get it to display the error message for the exchange rate to say " unable to convert to a number "

There are some flaws in your code:
you should prefer int.TryParse instead of Parse. An Exception should be an unexpected behavior, where you have to react in some way. A userinput is not unexpected, you know there's a chance that the use inputs invalid data which you can/have to validate.
When you use exceptions, you should not catch all exceptions at once, but some type of exception where you know how to react. int.Parse itself throws three kind of exceptions (see http://msdn.microsoft.com/de-de/library/b3h1hf19(v=vs.110).aspx), you can get some other ones from the system itself. Your code should catch FormatException instead of a catch-all.
anyway, if you just want to fix your code, you can solve your problem with using two seperate try .. catch blocks with seperated error messages.

Exceptions are there to catch the exceptional - the things you don't expect to happen but might
You should be using TryParse methods instead
while(!int.TryParse(Console.ReadLine(), out ivalue)
{
Console.WriteLine("Thats not a number, try again");
}

Related

Program exiting when using String.ToUpper(); on a string that has spaces in it

Let me start off saying that I'm new to C#.
I'm currently in the making of my first command-line application that in it's current state can do two things. One of them is a calculator, for which I need more learning to actually make it work, and the other is a string capitalizer.
I have a string nameCapInput = Console.Readline() that takes in the user input, which then gets analyzed to make sure that no digits are allowed:
using System;
using System.Linq;
namespace First_Console_Project
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("My first ever console application - 2020/2/26\n\n\n");
programSel:
Console.WriteLine("What do you want to do?\n");
Console.WriteLine("1. Calculate Numbers \n2. Capitalize Letters/Strings");
Console.WriteLine("Input your desired action:");
var inputVar = Console.ReadLine();
switch (inputVar)
{
case "1":
//Calculator code goes here
Console.WriteLine("Number 1 succeeded, opening calculator... Stand by");
Console.WriteLine("Calulator Loaded.");
Console.WriteLine("Doesn't work right now. Type \"exit\" to get back to the \"what do you want to do\" page.");
//Code goes here when I have learned the proper methods
calcInput:
var calcInput = Console.ReadLine();
if (calcInput == "exit")
{
goto programSel;
} else
{
Console.WriteLine("Unknown command. Type \"exit\" to get back to the \"what do you want to do\" page.");
goto calcInput;
}
case "2":
Console.WriteLine("Loading string capitalizer...");
Console.WriteLine("Type any string made of letters only without spaces, because if you use spaces, the program will exit. The output will make them all uppercase. Type \"exit\" to get back to the \"what do you want to do\" page.");
inputCap:
string nameCapInput = Console.ReadLine();
bool containsInt = nameCapInput.Any(char.IsDigit);
bool isMadeOfLettersOnly = nameCapInput.All(char.IsLetter);
if (nameCapInput == "exit")
{
goto programSel;
}
else if (containsInt)
{
Console.WriteLine("You can't capitalize numbers. Use letters only. Try again.");
goto inputCap;
}
else if (isMadeOfLettersOnly)
{
string upper = nameCapInput.ToUpper();
Console.WriteLine($"The uppercase version of your entered text is: {upper}");
goto inputCap;
}
break;
}
}
}
}
Now, everything works fine and it capializes everything I put into it except strings with spaces in them. When I type in a string with spaces in it, the program just exits with code 0. I'm not very good at C# yet, so I don't really know where to go from here. Any help is appreciated.
Every time I learn something new in C#, I try to implement it into my projects, so I can actually learn how to implement it to know when and how to use what I learned. This is an example for that.
EDIT: Added the rest of the code.
Thank you all very much. There's two things I have learned here:
goto is a bad habit
I absolutely need to start learning to debug my own code.
The crux of your problem is that you are only checking if the input contains letters (not spaces). An easy fix is to change your LINQ a bit.
bool isMadeOfLettersOnly = nameCapInput.All(c => char.IsLetter(c) || char.IsWhiteSpace(c));
So now input with letters or spaces will be considered valid.
In addition, your use of goto is a very bad idea. Generally there should never be any reason to use goto.
To fix this, use a while loop and a method:
public static void Main()
{
bool exit = false;
do {
exit = ProcessInput();
}
while(!exit);
}
private static bool ProcessInput()
{
string nameCapInput = Console.ReadLine();
bool containsInt = nameCapInput.Any(char.IsDigit);
bool isMadeOfLettersOnly = nameCapInput.All(c => char.IsLetter(c) || char.IsWhiteSpace(c));
if (nameCapInput.Equals("exit", StringComparison.CurrentCultureIgnoreCase))
{
return true; //exiting so return true
}
else if (containsInt)
{
Console.WriteLine("You can't capitalize numbers. Use letters only. Try again.");
}
else if (isMadeOfLettersOnly)
{
string upper = nameCapInput.ToUpper();
Console.WriteLine("The uppercase version of your entered text is: {0}", upper);
}
return false; //no exit, so return false
}
This is just a quick refactor, you could make it better.
Fiddle here
Check the documentation: https://learn.microsoft.com/en-us/dotnet/api/system.char.isletter?view=netframework-4.8
Based on the documentation of the IsLetter function, the space is not included in the return true cases.
I would suggest that you use regular expressions for this or change your last case to
else if (!containsInt)
{
var upper = nameCapInput.ToUpper();
Console.WriteLine($"The uppercase version of your entered text is: {upper}");
goto inputCap;
}
Also check the documentation of goto: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/goto
The goto statement transfers the program control directly to a labeled statement.
A common use of goto is to transfer control to a specific switch-case label or the default label in a switch statement.
The goto statement is also useful to get out of deeply nested loops.
You are not in any such case, so you shouldn't use it.

Simple C# login with 3 attempts [duplicate]

This question already has answers here:
How to add c# login attempts loop in console application?
(3 answers)
Closed 6 years ago.
I need to create a simple C# Sharp program that takes userid and password as input (type string). After 3 wrong attempts user should be rejected.
I have started but I'm not sure how the logic should be properly done.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace UserId
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Type username");
String UserId1 = Console.ReadLine();
Console.WriteLine("Type password");
String Pass = Console.ReadLine();
String UserIdCorrect = "test1";
String PassCorrect = "password1";
int MaxAttempts = 3;
Console.ReadKey();
if (UserId1 != UserIdCorrect && Pass != PassCorrect ) {
MaxAttempts++;
}
Console.ReadKey();
}
}
}
First of all, even before writing a single line of code, try to think about naming conventions for a minute or two. This is like "putting foam on your face before having a shave. You can get a shave even without the shaving foam but the experience wouldn't be nice". Try this link for more info [https://msdn.microsoft.com/en-us/library/ms229045(v=vs.110).aspx].
Now moving towards your question, if I have to only fulfill your requirement, this code will be suffice. Here I'm taking "valid" as an identifier for the correct credentials:
<code>
//Login Attempts counter
int loginAttempts = 0;
//Simple iteration upto three times
for (int i = 0; i < 3; i++)
{
Console.WriteLine("Enter username");
string username = Console.ReadLine();
Console.WriteLine("Enter password");
string password = Console.ReadLine();
if (username != "valid" || password != "valid")
loginAttempts++;
else
break;
}
//Display the result
if (loginAttempts > 2)
Console.WriteLine("Login failure");
else
Console.WriteLine("Login successful");
Console.ReadKey();
</code>
Just run the for loop 3 times and if still user enter the wrong entry than just disable the window .
I guess you are a beginner. I've commented the code.
int maxAttempts = 3;
// looping n (maxAttempts) times
for(int i = 0; i < maxAttempts; i++)
{
// get input and check it
}
// do what ever you want here.
// at least show up a message
Many ways. As HebeleHododo commented you could also use a while-loop and check with if-else if your maxAttempts is reached.

Why does the console close after my last input?

My program allows the user to put in 20 prices and to display the average of those values. Why does the console close after I enter my last input? Below is the code I'm running:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace machineproblem4
{
class Program
{
static void Main(string[] args)
{
int sum = 0;
double average = 0;
Console.WriteLine("\t\t\t INPUT PRICES \n");
int[] price = new int[20];
Console.WriteLine("\t\t\t Please enter 20 prices \n");
for (int ctr = 0; ctr < 20; ctr++)
{
Console.Write("Enter price {0} : ", ctr + 1);
price[ctr] = Convert.ToInt32(Console.ReadLine());
}
// [...calculate sum...]
//average
Console.WriteLine("\n----------------------------");
Console.WriteLine("||average of the prices||");
average = sum / 20;
Console.WriteLine("average of the prices: {0}", average);
//more code that outputs statistics about the inputs
//exit
//Edit: This is what fixed my problem
Console.WriteLine("press any key to exit ..");
Console.ReadKey();
}
}
}
use Console.Readline();
Read(), ReadLine() and ReadKey() are basically static methods, and they comes under the Console class. That's why we use these methods like:
Console.Read():-- method accept the String and return the integer.
Console.ReadLine():--method accept the String and return string .
Console.ReadKey():--method accept the Character and also return Character.
That's why we mostly use the Console.ReadKey() method, for come back to source code from output window .
Because when we only press the character we directly come on source code. If you will use the Console.Read() and Console.ReadLine method then
you need to press Enter, come back to the source code rather then any character.
You can place a Console.Read() at the last statement. You can also place a breakpoint at your last statement
Generally, it is not a good idea to wait for user input from a console application. This is okay for debugging, but not definitely for release.
So, first find out if your application is in debug or release config using
private static bool IsDebug()
{
object[] customAttributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(DebuggableAttribute), false);
if ((customAttributes != null) && (customAttributes.Length == 1))
{
DebuggableAttribute attribute = customAttributes[0] as DebuggableAttribute;
return (attribute.IsJITOptimizerDisabled && attribute.IsJITTrackingEnabled);
}
return false;
}
Then use,
if (IsDebug())
Console.Readline();
This eliminates the need to edit the code for different build configurations. Alternative is to put a breakpoint and debug the console app, as suggested by #Erwin
Put:
Console.Readline();
at the end of your main function, so it waits until you press enter before it closes.
None of the previous answers actually directly answer the question of why this is happening. The reason why the console is closing after your last input is that the rest of the code runs very quickly and when it reaches the end of your program, the console closes. This is correct behavior and should be expected when running a console application. As the other answers have stated, you can work around this by requiring a final input before closing the console, but that is all it is, a work around.
If you were to output to a text file rather than just the console, you would see that all of the output is generated as you would expect. The console output and close is just too fast for you to see it without some sort of pause in the code.
Additionally, a solution that has not been mentioned yet is to run the project from Visual Studio without debugging, which will automatically output "Press any key to continue..." when it finishes processing before closing the console. That way you can see what it is outputting without extraneous code that you wouldn't want to have in production code.

i want hide some character from email like Sha***aj#gmail.com [closed]

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 8 years ago.
Improve this question
I have developed a application, it is user based application. int this app if user forget his password, then user can reset his password only through his email id and in case if user is not remember his email id which is associated with his account at that time i want retrieve password in a social security numbers like sha***aj#gmail.com. How can i achieve this please help me with this problem that will be appreciated. Thank you.
i have got this code from stak over flow but it is not meet my requirement. It is good for only phone number not for email
public static string GetMaskedEmail(string number)
{
if (String.IsNullOrEmpty(number))
return string.Empty;
if (number.Length <= 12)
return number;
string last12 = number.Substring(number.Length - 12, 12);
var maskedChars = new StringBuilder();
for (int i = 0; i < number.Length - 12; i++)
{
maskedChars.Append(number[i] == '-' ? "-" : "#");
}
return maskedChars + last12;
}
Work is a little slow tonight, so I fired up Xamarin Studio and whipped this up for you. This shouldn't be taken as an example in best coding practices, really not at all.
Though what this will provide is a functioning example, from which you can take and build into your own method and hopefully learn in the process. A great resource for reference, if you get lost at all while reading over any code, is MSDN which if you haven't visited yet I would suggest doing so and bookmarking for future use.
using System;
namespace EmailHash
{
class MainClass
{
public static void Main (string[] args)
{
if (args.Length <= 0)
{
Console.WriteLine ("No values were passed to application.");
return;
}
string email = args[0];
int indexOfAt = email.IndexOf ("#");
if (indexOfAt == -1)
{
Console.WriteLine("Unable to find '#' symbol within email.");
return;
}
int indexStart = 3;
int indexEnd = indexOfAt - 2;
if (indexStart >= indexEnd)
{
Console.WriteLine("Not enough characters in email to mask value.");
return;
}
string hashedEmail = email.Replace(email.Substring(indexStart, indexEnd - indexStart), "***");
Console.WriteLine("Original email: " + email);
Console.WriteLine("Hashed email: " + hashedEmail);
return;
}
}
}

String FormatException

I'm doing an activity that asks your name, and if a number is inserted it should tell that the input is invalid.
Here's my code:
try {
Console.Write("Enter your first name: ");
string fname = Console.ReadLine();
Console.Write("You're Name is: " + fname);
}
catch (Exception) {
Console.Write("INVALID NAME");
}
Sample output:
Enter you're first name: 123hjay
INVALID NAME!!
I know my exception is wrong; I need your help guys.
You seem to have misunderstood the purpose of exceptions.
Exceptions are thrown when a program encounters an error in its execution. For example assigning a letter to an int would throw an error. While opinions vary, I tend not to handle user input errors with exceptions. Furthermore, think about the logic you wrote in your code. How could the program know that entering numbers into a variable named fname is incorrect?
Write in logic into your program to test for input errors and then return an appropriate response. In your case, if you wanted to ensure that there were no numbers entered, you could do the following:
if (name.Any(char.IsNumber))
{
Console.WriteLine("Invalid Name.");
}
Console.ReadLine();
As my comment says (in the question), I didn't really get what it is you are asking, because it doesn't throw anything, but if you did want it to throw an error (also suggested by the comments), this should help:
Console.Write("Enter you're first name: ");
string fname = Console.ReadLine();
foreach (var character in fname)
{
if (Char.IsDigit(character))
throw new Exception("Numbers are not allowed.");
}
Console.Write("You're Name is: " + fname);
It's very straight forward and you can read it as English and understand what I've done.
You can mess around with the code, look at similar functions with Visual Studios IntelliSense and tweak it to your needs.
If you need, add a try & catch blocks, of course.
for the courtesy of replying back, here is the answer.
Hint: your exception is right!
Enter in your console "Glee" it will not throw exception.
If you type "7337" it does throw exception.
try to use : fname.ToString();

Categories

Resources