checking integers in String - c#

I'm checking a string whether it has integers or anything else in function Parse().
Here is my Code
static public int input()
{
Console.WriteLine("Enter The Number Of Student You Want to get Record");
int x;
string inputString = Console.ReadLine();
if (int.TryParse(inputString, out x))
{
Console.WriteLine(inputString + " Is Integer");
return x= Convert.ToInt32(inputString);
}
else
{
input();
}
return x;
}
And full code is:
static void Main(string[] args)
{
int num = 0;
string[] names = new string[] { };
long[] fee = new long[] { };
string[] className = new string[] { };
do
{
Console.WriteLine("Enter Option You Want: \nA:Enter Student Record\nB:Display Student Record\nQ:Exit");
string option =null;
option =Console.ReadLine();
switch (option)
{
case "A":
case "a":
{
num = input();
names = new string[num];
fee = new long[num];
className = new string[num];
for (int i = 0; i < num; i++)
{
Console.WriteLine("Enter Name Of Student:{0}",i);
Console.Write("Enter Student Name: "); names[i] = Console.ReadLine();
Console.Write("Enter Student Fee: "); fee[i] = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter Student Class Name: "); className[i] = Console.ReadLine();
}
break;
}
case "B":
case "b":
{
for (int i = 0; i < names.Length; i++)
{
Console.WriteLine("Record of Student: {0}",i);
Console.WriteLine("Name: "+names[i]+ "\nFee: " + fee[i]+ "\nClass Name: " + className[i]);
//Console.WriteLine("Name: {0}\n Class Name: {1}\n Fee: {3}\n",names[i],className[i],fee[i]);
}
break;
}
case "Q":
case "q":
{
Environment.Exit(1);
break;
}
default:
{
Console.WriteLine("Invalid Option");
break;
}
}
} while (true);
}
But The problem is when I enters char instead of int and it works fine and calls itself again but if 2nd time or after 2nd time I input int then does not take input of students and instead it repeats the LOOP again.
So what's the problem, is problem in Input Function????

You could use a regular expression to find the INTs. Also you should call
return input();
instead of
input();
new method:
static public int input(){
Console.WriteLine("Enter The Number Of Student You Want to get Record");
string input = Console.ReadLine();
if (Regex.IsMatch(input, #"\d+"))
{
return int.Parse(Regex.Match(input, #"\d+").Value);
}
else
{
return input();
}
}

I'm assuming you're a student. I started out with C# doing the same stuff. Which I wouldn't do anymore but since you are doing it. I'd recommend using goto, making this method recursive is a no no.
static public int input()
{
Prompt:
Console.WriteLine("Enter The Number Of Student You Want to get Record");
int x;
string inputString = Console.ReadLine();
if (int.TryParse(inputString, out x))
{
Console.WriteLine(inputString + " Is Integer");
return x;
}
else
{
goto Prompt;
}
}

Related

Pass 2D Array Info to a method in c#

I have an assesment where we have to implement methods in an app to store employees info in a 2D array and display it onscreen. So far the code works ok like this but I can't figure out a way to pass the 2D array information to the case 2 of the switch. It always results in an IndexOutOfRangeException when I try to return the array info from the UserInput method or when creating a method for case 2 and trying to pass the array. This is the code i have, thanks in advance for the help:
using System;
namespace EmployeeFileWithMethods
{
class Program
{
static void Main(string[] args)
{
int numberEmployees = 0;
string[,] table = new string[numberEmployees, 4];
string userInput = "1";
while ( userInput != "0" )
{
userInput = Intro();
switch ( userInput )
{
case "1":
UserInput();
break;
case "2":
Console.Clear();
for ( int user = 0; user < table.GetLength(0); user++ )
{
Console.WriteLine(" User " + ( user + 1 ));
for ( int row = 0; row < table.GetLength(1); row++ )
{
Console.Write(table[user, row] + "\n");
}
Console.WriteLine("");
}
break;
case "0":
break;
default:
{
DefaultCase();
break;
}
}
}
Console.WriteLine("Thanks for using the app!");
Console.ReadLine();
}
public static string Intro()
{
Console.WriteLine("[-------------------------------------------------------------------------------]");
Console.WriteLine(" Welcome to the Edinburgh College App \n What would you like to do?\n 1:Add User\n 2:Show User Info\n 0:Exit");
Console.WriteLine("[-------------------------------------------------------------------------------]");
string userInput = Console.ReadLine();
return userInput;
}
public static void DefaultCase()
{
Console.Clear();
Console.WriteLine("[-------------------------------------------------------------------------------]");
Console.WriteLine(" The option that you entered is invalid. Please try again. ");
Console.WriteLine("[-------------------------------------------------------------------------------]");
}
public static void UserInput()
{
Console.WriteLine("How many employees does your company have?");
int numberEmployees = Convert.ToInt32(Console.ReadLine());
string[,] table = new string[numberEmployees, 4];
for ( int row = 0; row < numberEmployees; row++ )
{
Console.WriteLine("Write the Forename of user " + ( row + 1 ));
string forename = Console.ReadLine();
table[row, 0] = forename;
Console.WriteLine("Write the Surname of user " + ( row + 1 ));
string surname = Console.ReadLine();
table[row, 1] = surname;
while ( true )
{
Console.WriteLine("Write the Phone of user " + ( row + 1 ));
string phone = Console.ReadLine();
if ( phone.Length == 11 )
{
table[row, 2] = phone;
break;
}
else
{
Console.WriteLine("Invalid Phone Number. Please Try Again");
continue;
}
}
while ( true )
{
Console.WriteLine("Write the Email of user " + ( row + 1 ));
string email = Console.ReadLine();
int charPos = email.IndexOf('#');
if ( charPos > 0 )
{
table[row, 3] = email;
break;
}
else
{
Console.WriteLine("Invalid Email. Please Try Again");
continue;
}
}
}
}
}
}
I can't reproduce the exception, but UserInput returns nothing and the table initialized in this method is lost at the return. So the table in Main has a size for the first dim of 0. You should pass the table as a parameter by ref and remove the table declaration in the method:
UserInput(table);
public static void UserInput(ref string[,] table)
But you need to resize this array to add new inputs.
A better and more simple and robust and cleaner way is to use a list of a class entity. Here is the code adapted and improved to use a list of an employee entity. I touched the code a minimum but it can be improved and refactored more, especially the while loops, and also you can use int.TryParse for the number of employees to add.
using System.Collections.Generic;
public class Employee
{
public string Forename { get; set; }
public string Surname { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
}
static private void Main()
{
var employees = new List<Employee>();
string userInput = "1";
while ( userInput != "0" )
{
userInput = Intro();
switch ( userInput )
{
case "1":
UserInput(employees);
break;
case "2":
Console.Clear();
for ( int index = 0; index < employees.Count; index++ )
{
Console.WriteLine(" User " + ( index + 1 ));
Console.WriteLine(" Forename: " + employees[index].Forename);
Console.WriteLine(" Surname: " + employees[index].Surname);
Console.WriteLine(" Phone: " + employees[index].Phone);
Console.WriteLine(" eMail: " + employees[index].Email);
Console.WriteLine("");
}
break;
case "0":
break;
default:
{
DefaultCase();
break;
}
}
}
Console.WriteLine("Thanks for using the app!");
Console.ReadLine();
}
public static void UserInput(List<Employee> employees)
{
Console.WriteLine("How many employees does your company have?");
int countEmployees = employees.Count;
int countEmployeesNew = Convert.ToInt32(Console.ReadLine());
for ( int indexEmployeeNew = 0; indexEmployeeNew < countEmployeesNew; indexEmployeeNew++ )
{
int posEmployeeNew = countEmployees + indexEmployeeNew + 1;
Console.WriteLine("Write the Forename of user " + posEmployeeNew);
string forename = Console.ReadLine();
Console.WriteLine("Write the Surname of user " + posEmployeeNew);
string surname = Console.ReadLine();
string phone = "";
while ( true )
{
Console.WriteLine("Write the Phone of user " + posEmployeeNew);
phone = Console.ReadLine();
if ( phone.Length == 11 ) break;
Console.WriteLine("Invalid Phone Number. Please Try Again");
}
string email = "";
while ( true )
{
Console.WriteLine("Write the Email of user " + posEmployeeNew);
email = Console.ReadLine();
int charPos = email.IndexOf('#');
if ( charPos > 0 ) break;
Console.WriteLine("Invalid Email. Please Try Again");
}
employees.Add(new Employee
{
Forename = forename,
Surname = surname,
Phone = phone,
Email = email
});
}
}

C# Print an array of strings in the reverse order

so I have a problem where when I open my program and select 4 which is supposed to make it display all of the strings in the array but in reverse.
using System.Linq;
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace Homework3
{
class Program
{
static void Main(string[] args)
{
int optionIntOne;
int optionIntTwo;
int i;
int num = 0;
decimal k;
string[] names = {"Keyhan", "Adolf", "Niklas", "Jenny",
"Elisa", "Rudolf", "Bengt", "Hassan", "Kajsa", "Maggan"};
Console.WriteLine("Please Select an Option Below:\n1 - Find a student by Index \n" +
"2 - Find student Index by name\n3 - Display all student names with their Index \n" +
"4 - Display all the students in reverse order");
string optionStringone = Console.ReadLine();
bool isNumericOne = Int32.TryParse(optionStringone, out optionIntOne);
Console.Clear();
switch (optionIntOne)
{
case 1:
Console.WriteLine("***FIND Student by ID" + "\n" + "Please select a number between 0 - 9:");
string studentNumber = (Console.ReadLine());
bool isNumericTwo = Int32.TryParse(studentNumber, out optionIntTwo);
if (isNumericTwo == true && optionIntTwo < names.Length)
Console.WriteLine(names[optionIntTwo]);
else
Console.WriteLine("Please enter a valid number");
break;
case 2:
Console.WriteLine("*** FIND Student Index by Name \n Please Print one of the above names");
foreach (string name in names)
Console.WriteLine((name));
Console.WriteLine("\n");
string studentName = (Console.ReadLine().ToUpper());
//ToUpper så slipper loopen göra det på repeat
Console.Clear();
bool b = false;
if (decimal.TryParse(studentName, out k) || studentName == string.Empty)
{
Console.WriteLine("Please Enter a Valid Name");
}
else
{
for (i = 0; i < names.Length; i++)
{
if (names[i].ToUpper() == studentName)
{
b = true;
Console.WriteLine(names[i] + " Has the index of " + i);
break;
}
}
if (b == false)
Console.WriteLine("The Student does not Exist in the List");
}
break;
case 3:
while (num < names.Length)
{
Console.WriteLine(num + " - " + names[num]);
num++;
}
break;
case 4:
while (num < names.Length)
{
Console.WriteLine(names[num].Reverse());
num++;
}
break;
default:
Console.WriteLine("Enter a Valid Number");
break;
}
Console.ReadKey();
}
}
}
(option 3 but to print them in reverse order)
Visual Studio isnt giving me any errors but it outputs like this 1 instead of the reverse order of this 2
Anyone know how to fix?/could point out the problem
First of all this line:
Console.WriteLine(names[num].Reverse());
Is reversing the strings inside the list (so names[0].Reverse() would be "nahyeK") because string is also a list (a list of chars). If you want to reverse the whole list you only write names.Reverse();
read more at: Microsoft docs - Reverse()
So the next step would be to print it out.
When you do list.Reverse(); it will return IEnumerable<TSource> which you can use in a loop to get the names.
string[] names = {"Keyhan", "Adolf", "Niklas", "Jenny",
"Elisa", "Rudolf", "Bengt", "Hassan", "Kajsa", "Maggan"};
IEnumerable<string> reversedList = names.Reverse();
foreach(string name in reversedList)
{
Console.WriteLine(name);
}
I usually use list.Reverse().ToList() so i get a "normal" list again because it's in my opinion easier to use/understand.
There is some options, the namespace system.linq.enumerable got some stuff for that:
.ToArray() - converts it to an Array.
.ToList() - converts it to a List
So the complete solution would be to keep the .Reverse outside the loop like this:
foreach(name in names.Reverse().ToList())
{
Console.WriteLine(name);
}
Here is one option:
static void Main(string[] args)
{
int num = 0;
string[] names = { "Alice", "Bob", "Charles", "Delilah" };
while (num < names.Length)
{
Console.WriteLine(names.Reverse().ElementAt(num));
num++;
}
// Prints
//
// Delilah
// Charles
// Bob
// Alice
Console.ReadKey();
}
As per the comments it is not optimal to call Reverse() in each loop. Instead, perform the Reverse() outside of the loop.
A better alternative might be:
static void Main(string[] args)
{
string[] names = { "Alice", "Bob", "Charles", "Delilah" };
for (int num = names.Length - 1; num >= 0; num--)
{
Console.WriteLine(names[num]);
}
Console.ReadKey();
}

C# How can i use parameter function in my hangman game

I have been asked by my teacher to store my functions inside a parameter driven function and replacing the switch with an if statement. I have no idea how i am supposed to do this. Any help is appreciated.
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
namespace ConsoleApplication6
{
class Hangman
{
public static int lives = 5;
static string[] wordBank = { "study", "cat", "dress", "shoes", "lipstick" };
static ArrayList wordList = new ArrayList(wordBank);
static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.Title = "C# Hangman";
Console.WriteLine("Hang man!");
string response = "";
do
{
Console.Write("Enter Command (1. Add Words, 2. List Words , 3. Play , 4. Exit) Pick 1-4: ");
response = Console.ReadLine();
switch (response)
{
case "1":
AddWord();
break;
case "2":
ListWords();
break;
case "3":
Play();
break;
case "4":
break;
}
} while (response != "4");
}
static void AddWord()
{
Console.Write("Enter the word to add: ");
String temp = Console.ReadLine();
wordList.Add(temp);
Console.WriteLine("{0} was added to the dictionary!", temp);
}
static void ListWords()
{
foreach (Object obj in wordList)
Console.WriteLine("{0}", obj);
Console.WriteLine();
}
static void AskLives()
{
try
{
Console.WriteLine("please enter number of lives?");
lives = int.Parse(Console.ReadLine());
}
catch
{
AskLives();
}
}
static void Play()
{
Random random = new Random((int)DateTime.Now.Ticks);
string wordToGuess = wordList[random.Next(0, wordList.Count)].ToString();
string wordToGuessUppercase = wordToGuess.ToUpper();
StringBuilder displayToPlayer = new StringBuilder(wordToGuess.Length);
for (int i = 0; i < wordToGuess.Length; i++)
displayToPlayer.Append('-');
List<char> correctGuesses = new List<char>();
List<char> incorrectGuesses = new List<char>();
bool won = false;
int lettersRevealed = 0;
string input;
char guess;
AskLives();
while (!won && lives > 0)
{
Console.WriteLine("Current word: " + displayToPlayer);
Console.Write("Guess a letter: ");
input = Console.ReadLine().ToUpper();
guess = input[0];
if (correctGuesses.Contains(guess))
{
Console.WriteLine("You've already tried '{0}', and it was correct!", guess);
continue;
}
else if (incorrectGuesses.Contains(guess))
{
Console.WriteLine("You've already tried '{0}', and it was wrong!", guess);
continue;
}
if (wordToGuessUppercase.Contains(guess))
{
correctGuesses.Add(guess);
for (int i = 0; i < wordToGuess.Length; i++)
{
if (wordToGuessUppercase[i] == guess)
{
displayToPlayer[i] = wordToGuess[i];
lettersRevealed++;
}
}
if (lettersRevealed == wordToGuess.Length)
won = true;
}
else
{
incorrectGuesses.Add(guess);
Console.WriteLine("Nope, there's no '{0}' in it!", guess);
lives--;
}
Console.WriteLine(displayToPlayer.ToString());
}
if (won)
Console.WriteLine("You won!");
else
Console.WriteLine("You lost! It was '{0}'", wordToGuess);
Console.Write("Press ENTER to exit...");
Console.ReadLine();
}
}
}
Highlight the switch block and select "Quick Actions."
Rename the function after applying the change.

C# converting strings to int's

I'm new to c# and am trying to make a simple calculator.
It works fine until it goes back to the start to take a new number.
When taking the new number it says it cant convert the user input to a integer.
using System;
namespace simpleCalculator
{
class MainClass
{
public static void Main(string[] args)
{
start:
Console.Clear();
Console.WriteLine("Enter first number");
int x = Convert.ToConsole.ReadLine();
Console.WriteLine("Would you like to\n1. Add\n2. Multiply\n3. Devide");
string o = Console.ReadLine();
if (o == "1")
{
Console.WriteLine("Enter second number\n");
int y = Convert.ToInt32(Console.ReadLine());
add(temp, y);
goto start;
Console.Clear();
goto start;
}
}
public static void add(int num01, int num02)
{
Console.Clear();
Console.WriteLine((num01 + num02) + "\nPress enter to contiue.");
Console.Read();
}
}
}
Use TryParse so if the parsing fails, you will not get an exception.
var enteredValue = Console.ReadLine();
var parsedValue;
if (!int.TryParse(enteredValue, out parsedValue))
{
// parse failed do whatever you want
}
Do that for both entries and if both of them pass, then call your add method.
You're looking for int.Parse(). Be careful to validate your input. You should probably create an escape condition.
Edited to show an alternative solution
Edited to be more explicit on how to handle some input
class Program
{
public static void Main(string[] args)
{
string input = String.Empty;
int x = 0, y = 0;
while (true)
{
try
{
Console.WriteLine("Enter first number");
x = int.Parse(Console.ReadLine());
Console.WriteLine("Would you like to\n1. Add\n2. Multiply\n3. Divide");
input = Console.ReadLine();
Console.WriteLine("Please enter a second number");
y = int.Parse(Console.ReadLine());
}
catch
{
Console.WriteLine("Invalid input");
continue;
}
switch (input)
{
case "1":
Console.WriteLine($"{x} + {y} = " + add(x, y));
break;
case "2":
//TODO implement multiply case
break;
case "3":
//TODO implement divide case
break;
default:
Console.WriteLine("Invalid input");
break;
}
}
}
public static int add(int x, int y) => x + y;
}
Try this:
int numbers = Convert.ToInt32("1234");

C# problems with a for loop

Can someone tell me why this doesnt work. When I enter the loop it prints everything instead of one line and get the users input. It prints Enter the integer the account numberEnter the integer the account balanceEnter the account holder lastname
Got it working thanks everyone, but now the searchaccounts doesnt work
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class accounts
{
private int[] accountnum = new int[5]; //private accountnum array of five integer account numbers
private int[] accountbal = new int[5];//private balance array of five balance amounts
private string[] accountname = new string[5];//private accntname array to hold five last names
public void fillAccounts()
{
int bal;
int accountnumber;
string name;
for (int x = 0; x < 5; ++x)
{
Console.Write("Enter the integer the account number");
accountnumber = Console.Read();
Console.Write("Enter the integer the account balance");
bal = Console.Read();
Console.Write("Enter the account holder lastname");
name = Console.ReadLine();
accountnum[x] = accountnumber;
accountbal[x] = bal;
accountname[x] = name;
}
}
public void searchAccounts()
{
Console.WriteLine("Enter the account number");
int acctnum = Console.Read();
for (int x = 0; x < 6; ++x)
{
if (x < 5)
{
if (accountnum[x] == acctnum)
{
Console.WriteLine("Account #{0} has a balance of {1} for customer {2}", acctnum, accountbal[x].ToString("C"), accountname[x]);
break;
}
}
else
{
Console.WriteLine("You entered invalid account number");
}
}
}
public void averageAccounts()
{
int sum = 0;
int avg;
for (int x = 0; x < 5; ++x)
{
sum = accountbal[x] + sum;
}
avg = sum / 5;
Console.WriteLine("The average dollar amount is {0}", avg.ToString("c"));
}
}
class assignment3_alt
{
static void Main(string[] args)
{
accounts myclass = new accounts();
string userin;
myclass.fillAccounts();
int i = 0;
while (i != 1)
{//use the following menu:
Console.WriteLine("*****************************************");
Console.WriteLine("enter an a or A to search account numbers");
Console.WriteLine("enter a b or B to average the accounts");
Console.WriteLine("enter an x or X to exit program");
Console.WriteLine("*****************************************");
Console.Write("Enter option-->");
userin = Console.ReadLine();
if (userin == "a" || userin == "A")
{
myclass.searchAccounts();
}
else if (userin == "b" || userin == "B")
{
myclass.averageAccounts();
}
else if (userin == "x" || userin == "X")
{
break;
}
else
{
Console.WriteLine("You entered an invalid option");
}
}
}
}
}
Console.Read only reads a single character. You need to use Console.ReadLine.
Console.Write("Enter the integer the account number");
accountnumber = int.Parse(Console.ReadLine());
Console.Write("Enter the integer the account balance");
bal = int.Parse(Console.ReadLine());
Console.Write("Enter the account holder lastname");
name = Console.ReadLine();
You might also want to consider using int.TryParse instead of int.Parse so that you can better handle invalid input.
For your new question it is the same error. Just replace:
int acctnum = Console.Read();
with
int acctnum = int.Parse(Console.ReadLine());
or (preferably)
int acctnum;
if (!int.TryParse(Console.ReadLine(), out acctnum))
{
Console.WriteLine("You need to enter a number");
return;
}
The first will fail if the user doesn't enter a valid integer the second will print out a nice error message and return to the loop.
This is not an answer, as other have already put up some good ones. These are just a few tips about your code.
Instead of looping with while (i != 1), never changing the value of i and terminating the loop with break, it would be better to use a do-while loop, like this:
do
{
// blah blah
} while(userin != "x" || userin != "X")
It is less confusing than having a variable with no use at all.

Categories