Using Case Break to convert string to int C# [duplicate] - c#

This question already has answers here:
Unreachable code detected in case statement
(14 answers)
Closed 7 years ago.
I'm trying to convert string to int. I think I have it right, but what else do I need to do? Under "Break" I get a green line saying "unreachable code detected". Also, what do I tell it to return? I put a random number after return, because I have blanked on what I should ask it to return.
namespace BattleShip.UI
{
class TranslateNumberToLetter
{
public int NumberToLetter(string Letter)
{
switch (Letter)
{
case "A":return 1;
break;
case "B": return 2;
break;
case "C": return 3;
break;
case "D": return 4;
break;
case "E": return 5;
break;
case "F": return 6;
break;
case "G": return 7;
break;
case "H": return 8;
break;
case "I": return 9;
break;
case "J": return 10;
break;
default: return -100;
}
}
}
}

public int NumberToLetter(string Letter)
{
if ("ABCEDFGHIJ".Contains(Letter))
return "ABCEDFGHIJ".IndexOf(Letter) + 1;
return -100;
}

Related

Switch case for comparing which number is higher given by user C#

I want to write a code in C# that asks a user to input 2 numbers to compare which is higher but cant seem to get an output from this.
{
class Program
{
public static int Max { get; private set; }
static void Main(string[] args)
{
Console.WriteLine("Please enter 2 (two) integer numbers on a separate line: ");
int num1 = int.Parse(Console.ReadLine());
int num2 = int.Parse(Console.ReadLine());
switch (Max)
{
case 1:
if (num1 < num2)
{
Console.WriteLine(num2 + "is Maximum");
}
break;
case 2:
if (num1 > num2)
{
Console.WriteLine(num1 + "is Maximum");
}
break;
}
}
}
}
You are using the "Max" variable on the condition of the switch, but you never actually declare "Max", and the switch is only expectating the numbers 1 or 2, because you put case 1: and case 2:
So the correct way to show output is this:
if(num1 > num2)
{
Max = 1;
}
else
{
Max = 2;
}
switch(Max)
{
case 1:
Console.WriteLine(num1 + "is Maximum");
break;
case 2:
Console.WriteLine(num2 + "is Maximum");
break;
}
This is just in case you need to use a switch case, because you can do it only with a simple if
case cannot be used to compare values of two numbers you might just want to use if-else statement or if you just want a application of case statement use this :
switch (input)
{
case 1:
Console.WriteLine("a");
break;
case 2:
Console.WriteLine("b");
break;
case 3:
Console.WriteLine("c");
break;
case 4:
Console.WriteLine("d");
break;
case 5:
Console.WriteLine("e");
break;
case 6:
Console.WriteLine("f");
break;
case 7:
Console.WriteLine("g");
break;
default:
Console.WriteLine("Invalid input");
break;
}

C# Case Sensitivity in Switch-statement

I'm working a little with switch statements and want to know how to ignore the case sensitivity when it comes to input values.
Here is my code:
using System;
namespace SwitchStatements
{
class MainClass
{
public static void Main(string[] args)
{
Start:
Console.WriteLine("Please Input the Grade");
char grade = Convert.ToChar(Console.ReadLine());
switch (grade)
{
case 'A':
Console.WriteLine("Excellent Work!");
break;
case 'B':
Console.WriteLine("Very Good Effort! Just a couple of Errors =)");
break;
case 'C':
Console.WriteLine("You Passed. Push Yourself Next Time");
break;
case 'D':
Console.WriteLine("Better put in more effort next time. I know you can do better");
break;
default:
Console.WriteLine("Invalid Grade.");
break;
}
Console.ReadKey();
goto Start;
}
}
}
If I put 'a' in instead of 'A' it returns the default response.
Can I use perhaps a .Comparison of some sort? If so where would I put it?
You can use ConsoleKey as condition for switch, the code will be like the following.
var grade =Console.ReadKey().Key;
switch (grade)
{
case ConsoleKey.A:
Console.WriteLine("Excellent Work!");
break;
case ConsoleKey.B:
// Something here
break;
case ConsoleKey.C:
// Something here
break;
case ConsoleKey.D:
// Something here
break;
case ConsoleKey.E:
// Something here
break;
default:
// Something here
break;
}
So that you can avoid converting the input to uppercase/Lower case, and then it goes for another conversion To Char. Simply use ConsoleKey Enumeration inside the switch.
You can use ToUpper(); Like
Convert.ToChar(Console.ReadLine().ToUpper());
and to get saved from the error of getting more charaters with Console.ReadLine() you can use
char grd = Convert.ToChar(Console.ReadKey().KeyChar.ToString().ToUpper());
you can use like following also
char grade = Convert.ToChar(Console.ReadLine().ToUpperInvariant());
https://msdn.microsoft.com/en-us/library/system.string.toupperinvariant.aspx
Convert to uppercase before switch like below,
grade = Char.ToUpper(grade);
Change
char grade = Convert.ToChar(Console.ReadLine());
To
char grade = Convert.ToChar(Console.ReadLine().ToUpper());
https://msdn.microsoft.com/en-us/library/system.string.toupper(v=vs.110).aspx
Write Switch on grade.ToUpper() like this and don't change change it's value, may be you will need it after
char grade = Convert.ToChar(Console.ReadLine());
switch (grade.ToUpper())
{
case 'A':
Console.WriteLine("Excellent Work!");
break;
case 'B':
Console.WriteLine("Very Good Effort! Just a couple of Errors =)");
break;
case 'C':
Console.WriteLine("You Passed. Push Yourself Next Time");
break;
case 'D':
Console.WriteLine("Better put in more effort next time. I know you can do better");
break;
default:
Console.WriteLine("Invalid Grade.");
break;
}
You may fall from one case to another like this
public static void Main(string[] args)
{
Boolean validInputRead = false;
Char grade;
while(!validInputRead)
{
validInputRead = true;
Console.WriteLine("Please Input the Grade");
grade = Convert.ToChar(Console.Read());
switch (grade)
{
case 'A':
case 'a':
Console.WriteLine("Excellent Work!");
break;
case 'B':
case 'b':
Console.WriteLine("Very Good Effort! Just a couple of Errors =)");
break;
case 'C':
case 'c':
Console.WriteLine("You Passed. Push Yourself Next Time");
break;
case 'D':
case 'd':
Console.WriteLine("Better put in more effort next time. I know you can do better");
break;
default:
Console.WriteLine("Invalid Grade.");
validInputRead = false;
break;
}
Console.ReadKey();
}
}
EDIT
Changed from Console.ReadLine() to Console.Read() as suggested
Added while(!validInputRead) as requested
string letterGrade;
int grade = 0;
// This will hold the final letter grade
Console.Write("Input the grade :");
switch (grade)
{
case 1:
// 90-100 is an A
letterGrade = "A";
Console.WriteLine("grade b/n 90-100");
break;
case 2:
// 80-89 is a B
letterGrade = "B";
Console.WriteLine("grade b/n 80-89");
break;
case 3:
// 70-79 is a C
letterGrade = "C";
Console.WriteLine("grade b/n 70-79");
break;
case 4:
// 60-69 is a D
letterGrade = "D";
Console.WriteLine(" grade b/n 60-69 ");
break;
default:
// point whic is less than 59
Console.WriteLine("Invalid grade");
break;
}

How to save output to text file

I've made a program where I can decrypt some encrypted text, it does this by reading a text file and shifting the text one letter at a time, and it does this 26 times, but I can't get it to save and write the output to a text file, this is my code below, I would appreciate any help if possible, thank you
using System;
using System.IO;
namespace Assignment1
{
class MainClass
{
public static void Main(string[] args)
{
//Writing to the screen
Console.WriteLine("Welcome to the Ceaser Cipher Shift Program");
Console.WriteLine("Would You Like to Decrypt a File (y for yes/n for no)");
string userValue = Console.ReadLine();
//User's value is set to userValue
// if the user types "y", activate the decryption method
if (userValue.ToLower() == "y")
{
decryption();
}
// if the user types in "n", write "Goodbye" and close the program
if (userValue.ToLower() == "n")
{
Console.WriteLine("Goodbye");
Console.ReadLine();
Environment.Exit(0);
//Environment.exit closes the program
}
}
//Decryption method
public static void decryption()
{
//ShiftLine is equal to new char
char[] ShiftLine = new char[0];
//If the shift is smaller or equal to 25, continue to shift one at a time
for (int shift = 1; shift <= 26; shift++)
{
//This reads the encryptefd text file into the program
string textFile = #"C:\Users\Anthony\Desktop\caesarShiftEncoded.txt";
//The string "test" reads all the lines of the textFile
string[] text = File.ReadAllLines(textFile);
foreach (string line in text)
{
//Sets currentLetter to 0
int CurrentLetter = 0;
int[] ShiftNumbers = new int[line.Length];
ShiftLine = new char[line.Length];
foreach (char letter in line)
{
ShiftNumbers[CurrentLetter] = ConvertLetterToNumber(letter);
ShiftNumbers[CurrentLetter] = ShiftCipher(ShiftNumbers[CurrentLetter], shift);
ShiftLine[CurrentLetter] = ConvertNumberToLetter(ShiftNumbers[CurrentLetter]);
CurrentLetter++;
}
Console.WriteLine(string.Join("", ShiftLine));
}
//Console.WriteLine (textFile.Length);
Console.WriteLine("This is Shift No: {0}", shift);
}
Console.WriteLine("Which Shift Would You Like To Write to a Text File: ");
string userNumber = Console.ReadLine();
if (userNumber.ToLower() == "1 =< 26")
{
using (StreamWriter text = new StreamWriter("TextWrittenFile.txt"))
{
foreach (char line in ShiftLine)
{
text.WriteLine(ShiftLine);
File.WriteAllText("C:\Users\Anthony\Desktop\DecryptedText.txt", ShiftLine);
}
}
}
}
public static int ShiftCipher(int Number, int Shift)
{
if (Number == 27)
{
return 27;
}
else if (Number == 28)
{
return 28;
}
else if (Number > Shift)
{
return (Number - Shift);
}
else if (Number <= Shift)
{
return (26 + (Number - Shift));
}
else
{
return 0;
}
}
public static int ConvertLetterToNumber(char Letter)
{
switch (Char.ToLower(Letter))
{
case 'a':
return 1;
case 'b':
return 2;
case 'c':
return 3;
case 'd':
return 4;
case 'e':
return 5;
case 'f':
return 6;
case 'g':
return 7;
case 'h':
return 8;
case 'i':
return 9;
case 'j':
return 10;
case 'k':
return 11;
case 'l':
return 12;
case 'm':
return 13;
case 'n':
return 14;
case 'o':
return 15;
case 'p':
return 16;
case 'q':
return 17;
case 'r':
return 18;
case 's':
return 19;
case 't':
return 20;
case 'u':
return 21;
case 'v':
return 22;
case 'w':
return 23;
case 'x':
return 24;
case 'y':
return 25;
case 'z':
return 26;
case ' ':
return 27;
default:
return 0;
}
}
public static char ConvertNumberToLetter(int Number)
{
switch (Number)
{
case 1:
return 'a';
case 2:
return 'b';
case 3:
return 'c';
case 4:
return 'd';
case 5:
return 'e';
case 6:
return 'f';
case 7:
return 'g';
case 8:
return 'h';
case 9:
return 'i';
case 10:
return 'j';
case 11:
return 'k';
case 12:
return 'l';
case 13:
return 'm';
case 14:
return 'n';
case 15:
return 'o';
case 16:
return 'p';
case 17:
return 'q';
case 18:
return 'r';
case 19:
return 's';
case 20:
return 't';
case 21:
return 'u';
case 22:
return 'v';
case 23:
return 'w';
case 24:
return 'x';
case 25:
return 'y';
case 26:
return 'z';
case 27:
return ' ';
default:
return '0';
}
}
}
}
As your ShiftLine seems to be an array of chars it could be as simple as that:
File.WriteAllText("C:\Users\Anthony\Desktop\DecryptedText.txt", new string(ShiftLine));
(instead of your loop [btw: Your loop overwrites the file on any turn...])
Actually there are a few things you could improve.
If the user shall only be able to press y or n, you could use the Console.ReadKey() method instead of letting the user input a complete line of text. By using the overloaded method and specifying true as argument, you won't even see the pressed key on written into the console window (Console.ReadKey(true)).
So you could exchange the current if statements with switch (Console.ReadKey(true).Key) and build cases like case ConsoleKey.Y:
So the Main method would look something like that:
public static void Main(string[] args)
{
//Writing to the screen
Console.WriteLine("Welcome to the Ceaser Cipher Shift Program");
Console.WriteLine("Would You Like to Decrypt a File (y for yes/n for no)");
switch (Console.ReadKey(true).Key)
{
// if the user types "y", activate the decryption method
case ConsoleKey.Y:
decryption();
break;
// if the user types in "n", write "Goodbye" and close the program
case ConsoleKey.N:
default:
Console.WriteLine("Goodbye");
Environment.Exit(0);
break;
}
}
I guess the next thing you want to do is using Caesar cipher for encrypting/decrypting data.
Therefore you "just" need to shift every character and this can be done much easier than writing switch-case statements like you did. The idea behind this type of encryption is, that you take one character and replace it with another one which is offset characters away. Decrypting goes the other way.
So it would be much easier building one method that has the ability to do exactly that for a specified text.
There are two special cases you need to consider: What happens if the value you are looking at is on the lower boundary and you substract the offset (meaning, the "new" value would be lower than zero). The second one represents the same situation on the upper boundary.
These sitations can be resolved using either if statements or possibly easier by just looking at the rest of the division with the maximum value range. (text[i] + offset) % NumberOfPossibleCharacters should do the trick.
Knowing this you can easily build a method like the following one (where I have assumed, that there is no character with a value greater than 127):
static string Encrypt(string data, int offset)
{
string result = string.Empty;
for (int i = 0; i < data.Length; i++)
{
// Add the offset to the current character and just take the
// rest of the division by 127. Afterwards cast it back to a character
// (because it will be a number due to + and %)
result += (char)((data[i] + offset) % 127);
}
return result;
}
Be advised, that string operations like += will cause the creation of a new string each time so it is not a good example from an (memory)performance point of view. There is the better way of using the StringBuilder class.
I hope this hint's you in a better way of solving your homework ;-)

C# listbox error

I have a lstYourHand that has two cards in it, I loop through the listbox to get the values of both cards. I take the string value of the listbox item (strCardVal) and use a switch to give it an integer value (intCardVal). For some reason, when I run the code, the message Box at the end gives me the value 0 as a result, it does not register me giving it a value in the switch statement. My code is below:
Int32 intCardVal = 0;
String strCardVal;
Int32 intLoopCounter1;
for (intLoopCounter1 = 0; intLoopCounter1 == 1; intLoopCounter1++)
{
strCardVal = lstYourHand.SelectedItem.ToString();
switch (strCardVal)
{
case "2":
intCardVal = 2;
break;
case "3":
intCardVal = 3;
break;
case "4":
intCardVal = 4;
break;
case "5":
intCardVal = 5;
break;
case "6":
intCardVal = 6;
break;
case "7":
intCardVal = 7;
break;
case "8":
intCardVal = 8;
break;
case "9":
intCardVal = 9;
break;
case "10":
case "J":
case "Q":
case "K":
intCardVal = 10;
break;
case "A":
intCardVal = 11;
break;
}
}
MessageBox.Show(intCardVal.ToString());
Have a look at this part of your code:
for (intLoopCounter1 = 0; intLoopCounter1 == 1; intLoopCounter1++)
In fact this loop body never will be executed because of loop execution condition intLoopCounter1 == 1 (which is false at the very first iteration since intLoopCounter1 == 0 in the beginning) - so your intCardVal will not be modified.
I think you've kept in mind intLoopCounter1 <= 1 here.
Also note (as it was mentioned in comments) - this kind of errors is pretty easy can be found by using debugger.

How to add multi value in same case

i have problems when adding mullti values into same case:
this is my c# code
string input = combobox1.selectedvalue.ToString();
switch(input)
{
case "one";
return 1;
break;
case "two";
return 2;
break;
case "three" , "four": // error here
return 34;
break;
default:
return 0;
}
need your help for
Just use separate labels:
string input = combobox1.selectedvalue.ToString();
switch(input)
{
case "one":
return 1;
break;
case "two":
return 2;
break;
case "three":
case "four":
return 34;
break;
default:
return 0;
}
See switch:
Each switch section contains one or more case labels followed by one or more statements
You can you the fall though, read this for more information
so it's look like this
switch(input)
{
case "one":
return 1;
break;
case "two":
return 2;
break;
case "three":
case "four":
return 34;
break;
default:
return 0;
}
Right syntax is
case "three":
case "four":
return 34;
break;
instead
case "three" , "four":
return 34;
break;
From switch (C# Reference)
A switch statement includes one or more switch sections. Each switch
section contains one or more case labels followed by one or more
statements.

Categories