c# console type in capslock [duplicate] - c#

This question already has an answer here:
Console use CAPS for user input
(1 answer)
Closed 4 years ago.
I wanted to create a little "Terminal"-Game, where everything is in uppercase.
But when you type with console readline, the input isn't all uppercase, and i haven't found a solution yet.
So if i type "login" i want the console to type "LOGIN" in realtime.
At the moment, my code looks like this:
static void Main(string[] args)
{
slowType("TERMINALTEST V1.0 CORP", 50, 100);
Console.WriteLine();
slowType(">", 50, 100);
string temp = Console.ReadLine();
}
static void slowType(string input, int minvelo, int maxvelo)
{
Random temp = new Random();
for (int i = 0; i < input.Length; i++)
{
Console.Write(input[i]);
Thread.Sleep(temp.Next(minvelo, maxvelo));
}
}
and i want to replace
string temp = Console.ReadLine();
with
string temp = MethodForTypingUppercase();

This will take each character 1 at a time, exit if enter is pressed, else we uppercase it, suppress the original character, and then write the uppercased version.
static void Main(string[] args)
{
string test = GetCapitalizedInput();
Console.WriteLine("Captured: " + test);
Console.ReadLine();
}
static string GetCapitalizedInput()
{
string input = "";
while (true)
{
var keypress = Console.ReadKey(true); // suppress original output
if (keypress.Key == ConsoleKey.Enter)
{
break;
}
string uppercased = keypress.KeyChar.ToString().ToUpper();
input += uppercased;
Console.Write(uppercased);
}
return input;
}

Related

This console app code runs once then close when i hit enter but i need it to be continious wht would i change? [duplicate]

This question already has answers here:
How to loop a Console.ReadLine?
(5 answers)
Closed 3 years ago.
My goal is to have the user input a number then add 5 to that number then display result to user and I want this to occur more than once
class Program
{
public Queue VisitedQueue = new Queue();
public Program myprogram = new Program();
static void Main()
{
int M = Main1();
Console.WriteLine(M); // display M
Console.ReadKey();
}
static int Main1()//get user number input and add 5 store as M
{
string H;
int M;
H = Console.ReadLine();
M = Convert.ToInt32(H) + 5;
return M;
}
}
I want this to occur more than once.
for achieving this goal you have to use loop in c#. for learning, loops follow this link.
and for this scenario that you define in question, you can try below code:
static void Main(string[] args)
{
Console.WriteLine("Please enter repeat time:");
var counter = int.Parse(Console.ReadLine());
for (var i = 0; i < counter; i++)
{
Console.WriteLine("Please enter your number:");
var number = int.Parse(Console.ReadLine());
Console.WriteLine($"{number} + 5 = {number +5}");
}
Console.ReadLine();
}
feel free to ask questions. good luck

How do I search an int array vs a string array by comparing it to user input

How do I check if user input matches a number in an array?
I've learned to compare user input or search using a string array, however doing the same with an int array is not working for me.
zipCode[i] = 0;
int userZip = 0;
do
{
Console.WriteLine( "enter a 5 digit zip code to see if it is supported in our area." );
Console.WriteLine( );
Console.WriteLine( "Enter a 0 to exit the program" );
userZip = 0;
if ( userZip == zipCode[i] )
{
found = true;
if ( found )
{
Console.WriteLine( "We support zip code {0}", userZip ); ;
}
else
{
Console.WriteLine( "We do not support", userZip );
}
}
} while ( userZip != 0 );
Console.ReadLine( );
How do I check if user input matches a number in an array?
using System;
using System.Collections.Generic;
public class Program
{
static List<string> _zipCodes;
static Program()
{
_zipCodes = new List<string>() { "80205", "80225", "80210" };
}
static void Main(string[] args)
{
string userZip = string.Empty;
do
{
Console.WriteLine("enter a 5 digit zip code to see if it is supported in our area.");
Console.WriteLine();
Console.WriteLine("Enter a -1 to exit the program");
userZip = Console.ReadLine();
if (_zipCodes.Contains(userZip))//<---------------THAT WAY
{
Console.WriteLine("We support zip code {0}", userZip); ;
}
else
{
Console.WriteLine("We do not support zip code {0}", userZip);
}
} while (userZip != "-1");
}
}
How do I check if user input matches a number in an array?
I will answer this question, though I can't post an example using your sample code since it's incomplete and it's not exactly clear what it's supposed to do.
First, let's create a method that gets an integer from the user. This method will continually loop until the user enters a valid integer:
public static int GetIntFromUser(string prompt = null)
{
int input;
int row = Console.CursorTop;
int promptLength = prompt?.Length ?? 0;
do
{
Console.SetCursorPosition(0, row);
Console.Write(prompt + new string(' ', Console.WindowWidth - promptLength - 1));
Console.CursorLeft = promptLength;
} while (!int.TryParse(Console.ReadLine(), out input));
return input;
}
Now, we can use that method to get the zip code from the user:
int userZipCode = GetIntFromUser("Enter a 5 digit zip code to see if it's supported: ");
Now I'm assuming you have an array of zip codes that are supported. Perhaps something like:
private static int[] GetSeattleZipCodes()
{
return new []
{
98101, 98102, 98103, 98104, 98105, 98106, 98107, 98108, 98109, 98110,
98111, 98112, 98113, 98114, 98115, 98116, 98117, 98118, 98119, 98121,
98122, 98124, 98125, 98126, 98127, 98129, 98131, 98133, 98134, 98136,
98138, 98139, 98141, 98144, 98145, 98146, 98148, 98154, 98155, 98158,
98160, 98161, 98164, 98165, 98166, 98168, 98170, 98174, 98175, 98177,
98178, 98181, 98185, 98188, 98190, 98191, 98194, 98195, 98198, 98199
};
}
So, now we have an int user input, and an int[] of valid zip codes, so to see if the array of valid zip codes contains the user zip code, we can just use the Contains method:
int[] seattleZipCodes = GetSeattleZipCodes();
bool found = seattleZipCodes.Contains(userZipCode);
TheFastCat beat me, but:
using System;
using System.Collections.Generic;
namespace ConsoleApplication1
{
class Program
{
private static IEnumerable<string> zipCodes = new string[] { "90210", "94102", "98101", "80014" };
static void Main(string[] args)
{
Console.WriteLine("enter a 5 digit zip code to see if it is supported in our area, or '0' to exit");
do {
// Read next line
string userZip = Console.ReadLine().Trim();
// Exit program?
if (userZip == "0")
break;
// Validate input
if (userZip.Length != 5)
{
Console.WriteLine("ERROR: Zip code {0} is {1} characters; expected 5", userZip, userZip.Length);
continue;
}
int n;
bool isNumeric = int.TryParse(userZip, out n);
if (!isNumeric)
{
Console.WriteLine("ERROR: Zip code {0} must be numeric", userZip);
continue;
}
// Finally, see if our zip code matches a zip code in the list
bool found = zipCodes.Contains(userZip);
if (found)
{
Console.WriteLine("We support zip code {0}", userZip); ;
}
else
{
Console.WriteLine("We do not support " + userZip);
}
} while (true);
Console.WriteLine("Done: exiting program");
}
}
}
Note:
Initializing the list
Validating the input
Using IEnumerable.Contains() ... without necessarily messing with LINQ.
Use of "break" and "continue" to control the loop, without necessarily needing an extraneous variable.
An int array is Enumerable<int>, so you could just use Contains(): https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.contains?view=netframework-4.7.2
TheFastCat and Rufus L done great job.
I just want to add an example. Using 'var' datatypes makes things easy and durable as well in C#
This example demonstrates both 'int' and 'string' using var datatypes in both cases. Good luck haberjin.
static void Main(string[] args)
{
//var ZipCodes = new List<string>() { "04846", "40569", "76859","54896", "84623" }; // ZipCodes are stored as a string in a List
var ZipCodes = new List<int>() { 04846, 40569, 76859, 54896, 84623 }; // ZipCodes are stored as an int in a List
//var userZip = "";
var userZip = 0;
do
{
Console.WriteLine("Enter a 5 digit zip code to see if it is supported in our area.");
//userZip = Console.ReadLine(); // Enable to receive userZip as a string
userZip = int.Parse(Console.ReadLine()); // receive userZip as an int
if (ZipCodes.Contains(userZip))
{
Console.WriteLine("We support zip code {0}", userZip);
}
else
{
Console.WriteLine("We do not support", userZip);
}
//} while (userZip != "0");
} while (userZip != 0);
}

In C#, How can I determine if a given string is a palindrome or not? [duplicate]

This question already has answers here:
Check if a string is a palindrome
(33 answers)
Closed 6 years ago.
I'm currently wondering if when a given string (word), how can I determine if it is a palindrome or not. A palindrome is a word or phrase that is the same if read forward or backward. I think I can solve this by looping through the half the word and comparing each letter with the other half. An example for this could be: (word[0] == word[word.Length-1-0]) would compare the first letter with the last letter of word, and (word[1] == word[word.Length-1-1]) would compare the second letter with the second to last letter.
Example Input could be: racecar
Example Output: True
Am I approaching this problem correctly towards the proper solution?
Here's a bit of I've written down so far.
public bool Test6(string word)
{
for (int i = 0; i < word.Length; i++)
{
if (word[0] == word[word.Length - 1 - 0])
{
}
I would do this (quickly).
string input = "..."
string reverse = new string(input.ToCharArray().Reverse().ToArray());
if(input.Equals(reverse)
{
// polindrome.
}
Please follow this link http://www.dotnetperls.com/palindrome
You can do it using this example without using any built in method :
using System;
class Program
{
public static bool IsPalindrome(string value)
{
int min = 0;
int max = value.Length - 1;
while (true)
{
if (min > max)
{
return true;
}
char a = value[min];
char b = value[max];
if (char.ToLower(a) != char.ToLower(b))
{
return false;
}
min++;
max--;
}
}
static void Main()
{
string[] array =
{
"civic",
"deified",
"deleveled",
"devoved",
"dewed",
"Hannah",
"kayak",
"level",
"madam",
"racecar",
"radar",
"redder",
"refer",
"repaper",
"reviver",
"rotator",
"rotor",
"sagas",
"solos",
"sexes",
"stats",
"tenet",
"Dot",
"Net",
"Perls",
"Is",
"Not",
"A",
"Palindrome",
""
};
foreach (string value in array)
{
Console.WriteLine("{0} = {1}", value, IsPalindrome(value));
}
}
}
A shorter version using LINQ would be
bool IsPalindrome(string x)
{
return Enumerable.Range(0,x.Length/2).All(e => x[e] == x[x.Length-1-e]);
}
Please find the code below
using System;
using System.Linq;
class MyClass
{
static void Main(string[] args) {
string str = Console.ReadLine();
string backwardsGuy = new string(str.Reverse().ToArray());
if(str==backwardsGuy)
{
Console.WriteLine("True");
}
else
{
Console.WriteLine("False");
}
}
}
Sample code-
static void Main(string[] args)
{
string s,revs="";
Console.WriteLine(" Enter string");
s = Console.ReadLine();
for (int i = s.Length-1; i >=0; i--) //String Reverse
{
revs += s[i].ToString();
}
if (revs == s) // Checking whether string is palindrome or not
{
Console.WriteLine("String is Palindrome \n Entered String Was {0} and reverse string is {1}", s, revs);
}
else
{
Console.WriteLine("String is not Palindrome \n Entered String Was {0} and reverse string is {1}", s, revs);
}
Console.ReadKey();
}

Restricting user input to numbers only

Brand new to C# [4 hours new :)], but hoping for some pointers on a Board Feet Calculator restricting the user input to only numbers, not allow letters or special characters.
First, does the restriction take place in the Class, Method, and/or Program? (I believe Class and Method)
Second, I've seen an example below, would I use something similar to this?
Third, if so, do I need to make separate classes for KeyPress and KeyPressEventArgs? (I believe they automatically there e.g.
public char KeyChar { get; set; }
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
// allows only letters
if (!char.IsLetter(e.KeyChar))
{
e.Handled = true;
}
}
My Program
namespace BoardFt_MyTry_
{
class Program
{
static void Main(string[] args)
{
Board board = new Board();
board.lengthOfboard = Convert.ToDouble(askQuestion("What is the length of your board in inches?"));
board.widthOfboard = Convert.ToDouble(askQuestion("What is the width of your board in inches?"));
board.thicknessOfboard = Convert.ToDouble(askQuestion("What is the thickness of your board in inches?"));
Console.WriteLine("Your board has {0} board feet.", board.CalcBoardFt());
Console.ReadLine();
}
private static string askQuestion(string question)
{
Console.WriteLine(question);
return Console.ReadLine();
}
}
My Board Class
namespace BoardFt_MyTry_
{
class Board
{
public double lengthOfboard;
public double widthOfboard;
public double thicknessOfboard;
public double CalcBoardFt()
{
double boardft = 0;
boardft = (this.lengthOfboard * this.widthOfboard * this.thicknessOfboard) / 144;
return boardft;
}
}
}
You can't really do that in a console application. All you can do is allow the user to input the bad data, then tell the user that the data is bad.
You can try something like this:
class Program
{
public double AskDnoubleQuestion(string message){
do {
Console.Write(message);
var input = Console.ReadLine();
if (String.IsNullOrEmpty(input)){
Console.WriteLine("Input is required");
continue;
}
double result;
if (!double.TryParse(input, out result)){
Console.WriteLine("Invalid input - must be a valid double");
continue;
}
return result;
}
static void Main(string[] args)
{
Board board = new Board();
board.lengthOfboard = AskDoubleQuestion("What is the length of your board in inches?");
board.widthOfboard = AskDoubleQuestion(askQuestion("What is the width of your board in inches?");
board.thicknessOfboard = AskDoubleQuestion(askQuestion("What is the thickness of your board in inches?");
Console.WriteLine("Your board has {0} board feet.", board.CalcBoardFt());
Console.ReadLine();
}
In case validation is not the way you want to proceed, you could do something like this:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter a number:");
string number = ReadNumber();
Console.WriteLine("You entered: " + number);
}
private static string ReadNumber()
{
string input = "";
do
{
ConsoleKeyInfo keyInfo = Console.ReadKey(true);
if (char.IsNumber(keyInfo.KeyChar))
{
input = input + keyInfo.KeyChar;
Console.Write(keyInfo.KeyChar);
}
if (keyInfo.Key == ConsoleKey.Enter)
{
Console.WriteLine();
break;
}
if (keyInfo.Key == ConsoleKey.Backspace)
{
input = input.Substring(0, input.Length - 1);
Console.Write("\b \b");
}
} while (true);
return input;
}
}
This will allow the user to enter only numbers. You could filter it anyway you want, if you wanted to. For example, only letters and numbers, etc...
As it stands right now, it only allows integer numbers. If you want to allow a decimal point, change the line above to this: if (char.IsNumber(keyInfo.KeyChar) || keyInfo.KeyChar == '.')
You could write a method that reads key by key (not displaying in the console), ignores non-numeric characters, prints valid characters and appends them to a StringBuilder instance, like so:
public static string ReadOnlyNumbers()
{
StringBuilder input = new StringBuilder();
ConsoleKeyInfo ckey;
while ((ckey = Console.ReadKey(true)).Key != ConsoleKey.Enter)
{
if (Char.IsDigit(ckey.KeyChar))
{
Console.Write(ckey.KeyChar);
input.Append(ckey.KeyChar);
}
if (ckey.Key == ConsoleKey.Backspace)
{
input.Length--;
Console.Write("\b \b");
}
}
Console.Write(Environment.NewLine);
return input.ToString();
}
You could then use it like this:
string input = ReadOnlyNumbers();
Console.WriteLine(input);

How can I fill an array with user input in case of numbers

I would like my program to fill an array with user input, but with an numeric input (then program will make specific calculations with that numbers, but it's not important for now).
If no input is done, program should stop reading numbers and print it. I have a couple of errors, especially in case of parsing, because I have tried a couple of solutions, and I have no idea in which part of code and maybe what way, numbers in an array should be parsed to avoid receiving an "cannot implicitly convert type string to int" or "cannot implicitly convert type int[] to int".
This how my code looks like:
public static void Main (string[] args)
{
int[] userInput = new int[100];
int xuserInput = int.Parse (userInput);
for (int i = 0; i<userInput.Length; i++)
{
userInput[i] = Console.ReadLine ();
if (userInput == "")
break;
}
Console.WriteLine (userInput);
}
you should take the input to a string and try to parse it to integer:
public static void Main(string[] args)
{
int[] userInput = new int[100];
int counter = 0;
for (counter = 0; counter < userInput.Length; counter++)
{
string input = Console.ReadLine();
if (input == "")
break;
else
int.TryParse(input, out userInput[counter]);
}
for (int i = 0; i < counter; i++)
{
Console.WriteLine(userInput[i]);
}
Console.ReadLine();
}
try parse will not throw exception like parse will.
if you decide to use parse, catch exceptions
Try this:
int[] userInputs = new int[100];
int parsedInput;
int inputs = 0;
bool stop = false;
while (inputs < 100 && !stop)
{
string userInput = Console.ReadLine();
if (userInput == "")
{
stop = true;
}
else if (Int32.TryParse(userInput, out parsedInput))
{
userInputs[i] = parsedInput;
inputs++;
}
else
{
Console.WriteLine("Please enter a number only!");
}
}
for each (int number in userInputs)
{
Console.WrietLine(number.ToString());
}
This code does a few things.
First, a while loop is used to ensure the user inputs 100 numbers or doesn't enter any data.
Next, it gets the input from the user. If it's an empty input, it sets the stop flag to true, which will exit the loop.
If the input wasn't empty, it uses TryParse to determine if the input is a number. If it is, it returns true and the converted input is added to the array and the counter incremented.
If the parse fails, the user is prompted to enter a number.
Once the array is filled, it loops through the array and prints out each input.
The problem is that you are parsing userInput which is an array with int.Parse instead of parsing the input you got by Console.ReadLine()
int xuserInput = int.Parse (userInput); // Remove this statement.
For parsing user input you need to parse like this
string input = Console.ReadLine ();
if (input == "")
break;
else
int.TryParse(input, out userInput[i]);
try this.
public static void Main (string[] args)
{
int[] userInput = new int[100];
int xuserInput = int.Parse (userInput);
for (int i = 0; i<userInput.Length; i++)
{
int temp = int.Parse(Console.ReadLine());
userInput[i] = temp;
if (userInput == "")
break;
}
Console.WriteLine (userInput);
}
You just might want to use this
static void Main(string[] args)
{
int[] userInput = new int[100];
string recievedInput = "";
for (int i = 0; i<userInput.Length; i++)
{
recievedInput = Console.ReadLine();
int.TryParse(recievedInput, out userInput[i]);
if (recievedInput == "")
break;
}
Console.WriteLine (userInput); //this will only print the type name of Userinput not all element
}
The following program reads numbers from user.
If user enters an invalid number, then it reports with the message: Not a valid number.
If user enters nothing, then the program prints all the numbers entered by the user.
class Program
{
static void Main(string[] args)
{
int[] userInput = new int[10];
for(int count = 0; count <= 9; count++)
{
int number;
string input = Console.ReadLine();
bool result = Int32.TryParse(input, out number);
if (result)
{
userInput[count] = number;
}
else if (!result)
{
if (input != string.Empty)
Console.WriteLine("Not a valid number.");
else if (input.Equals(string.Empty))
{
foreach (var item in userInput)
{
Console.WriteLine(item.ToString());
}
Console.WriteLine("Press any key to continue...");
Console.ReadKey(true);
return;
}
}
}
}
}
Please let me know, if this is okay to you.

Categories