How to ignore "Enter" key press in C# Console Application? - c#

using System;
using System.Text;
namespace 判断输入是否为数字
{
internal class Program
{
public static int ConsoleInputDigit(int length)
{
char[] news = new char[length];
for (int i = 0; i < news.Length; i++)
{
char temp = Console.ReadKey().KeyChar;
if (char.IsDigit(temp))
{
news[i] = temp;
}
else
{
Console.Write("\b \b");
i--;
}
}
return int.Parse(new string(news));
}
public static void Main(string[] args)
{
Console.Write("Input Year:");
int y = ConsoleInputDigit(4);
Console.Write("\nInput Month:");
int m = ConsoleInputDigit(2);
Console.Write("\nInput Day:");
int d = ConsoleInputDigit(2);
}
}
}
This ConsoleApp is suppose to input year、month、day from Console. I want to disable key except digital numbers(0-9).
Now this is my code, generally, it works.
But, for example, I want to input "2020" to year, when I input "202" and press Enter, the cursor will jump to the beginning of this line. It looks like the screenshot, Although it will not affect the final result.
I want to Console ignore the Enter key press(nothing happen), How to do that please?
My Sceenshot

This is how you can skip the enter key
internal class Program
{
public static int ConsoleInputDigit(int length)
{
char[] news = new char[length];
for (int i = 0; i < news.Length; i++)
{
var key = Console.ReadKey();
if (key.KeyChar.IsDigit(temp))
{
news[i] = temp;
}
else if(key == ConsoleKey.Enter)
{
// ignore
}
else
{
Console.Write("\b \b");
i--;
}
}
return int.Parse(new string(news));
}
public static void Main(string[] args)
{
Console.Write("Input Year:");
int y = ConsoleInputDigit(4);
Console.Write("\nInput Month:");
int m = ConsoleInputDigit(2);
Console.Write("\nInput Day:");
int d = ConsoleInputDigit(2);
}
}

Related

How to make my program say that I'm close or far from the answer and then to input it again? C#

Here I have the program that selects random number for me to guess. How can I make it now to say that number is close or far away from original random selected by the program?
using System;
namespace higherlower_guesser
{
class Program
{
static void Main(string[] args)
{
Random rnd = new Random();
int randomNumber = rnd.Next(0, 100);
bool answerCheck = false;
int guessAttempts = 0;
while (answerCheck == false)
{
Console.Clear();
Console.WriteLine("Take a guess.");
guessAttempts++;
int enteredValue = int.Parse(Console.ReadLine());
if (enteredValue == randomNumber)
{
Console.WriteLine("Congratulations, the number in mind is {0}. You've had {1} attempts", randomNumber, guessAttempts);
answerCheck = true;
}
}
}
}
}
You need to define what "close" and "far" are for your app. You can do something like:
const int CloseRange = 10;
if (enteredValue <= CloseRange) { /* we are close! */ }
else { /* we are far! */ }

Returning array of objects from static function

I am making a basic Visual Studio project.
Easiest way to explain is to show the code.
using System;
using System.Collections.Generic;
namespace testing
{
class Program
{
static void Main(string[] args)
{
int amountOfCars = getAmountOfCars();
Car[] myCars = createCars(amountOfCars);
}
public static int getAmountOfCars (){
Console.WriteLine("Amount of Cars to enter");
int amountOfCars = Convert.ToInt32(Console.ReadLine());
return amountOfCars;
}
public static Car createCars(int amountOfCars)
{
Car[] myCars = new Car[amountOfCars];
for (int i = 0; i < amountOfCars; i++)
{
Console.WriteLine("Enter brand");
string brand = Convert.ToString(Console.ReadLine());
Console.WriteLine("Enter amount of wheels");
int amountOfWheels = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter amount of seats");
int amountOfSeats = Convert.ToInt32(Console.ReadLine());
myCars[i] = new Car(brand, amountOfWheels, amountOfSeats);
}
return myCars[amountOfCars];
}
}
}
This line
Car[] myCars = createCars(amountOfCars);
Throws the following error:
Cannot implicitly convert type testing.Car to testing.Car[]
So, I then tried this to convert over
Car[] myCars = (Car[]) createCars(amountOfCars);
But it still throws the error.
Essentially I am just trying to return the array of objects from createcar function, so that it can be used within the rest of the code.
What is the best practice to solve this?
You need to return an array from createCars():
public static Car[] createCars(int amountOfCars)
{
Car[] myCars = new Car[amountOfCars];
for (int i = 0; i < amountOfCars; i++)
{
Console.WriteLine("Enter brand");
string brand = Convert.ToString(Console.ReadLine());
Console.WriteLine("Enter amount of wheels");
int amountOfWheels = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter amount of seats");
int amountOfSeats = Convert.ToInt32(Console.ReadLine());
myCars[i] = new Car(brand, amountOfWheels, amountOfSeats);
}
return myCars;
}
The signature of the function is
public static Car createCars(int amountOfCars)
instead of
public static Car[] createCars(int amountOfCars)
Also return just the array
return myCars;
instead of
return myCars[amountOfCars]; // This returns only one object at the amountOfCars index in the myCars array.
Also, this will trigger the ArrayIndexOutOfBoundsException as the myCars is allocated for amountOfCars and array spans from myCars[0] to myCars[amountOfCars-1]
funcion
public static int[] addFirst(int value, int count, int[] test)
{
test = test.Where(val => val != value).ToArray();
Array.Resize(ref test, test.Length + 1);
for (int i = count-1; i > 0; i--)
{
test[i] = test[i-1];
}
test[0] = value;
return test;
}
declaracion
array= addFirst(value, array.Length, array);

No errors in Visual Studio, Code Executes but something not right C# (updated! problem in String.Insert)

I'm writing a program for schoolwork, that's supposed to generate a 10 000 "movie" list. A single "movie" consist of a string in a form "moviename year director". I say "movie" because movie name and director are supposed to be randomly generated with letters from a-z.
I wrote the following logic to generate one such "movie". Movie name and director are random letter combination in length between 4-10 charachters. Code gives no errors in visual studio, executes, but shows blank. If I wrote correctly, then this code should generate one such string and print it, yet console is blank.
Do while loop is there to check if, however unlikely, there is a double item in the List (this is for when I do the 10 000 version).
In short, I dont understand what am I doing wrong?
using System;
using System.Collections.Generic;
using System.Linq;
namespace Experiment
{
class Program
{
static void Main(string[] args)
{
Movies();
Console.ReadKey();
}
public static void Movies()
{
List<string> movieList = new List<string>();
bool check = false;
do
{
string movie = "";
for (int i = 0; i < GetNum(); i++)
{
movie.Insert(0, Convert.ToString(GetLetter()));
}
movie.Insert(0, " ");
movie.Insert(0, Convert.ToString(GetYear()));
movie.Insert(0, " ");
for (int i = 0; i < GetNum(); i++)
{
movie.Insert(0, Convert.ToString(GetLetter()));
}
if (movieList.Contains(movie))
{
check = false;
}
else
{
movieList.Add(movie);
check = true;
}
} while (check == false);
Console.WriteLine(movieList[0]);
}
public static Random _random = new Random();
public static char GetLetter()
{
int num = _random.Next(0, 26);
char let = (char)('a' + num);
return let;
}
public static int GetNum()
{
int num = _random.Next(4, 11);
return num;
}
public static int GetYear()
{
int num = _random.Next(1920, 2020);
return num;
}
}
}
Strings are immutable, so calling the Insert() method on the movie string doesn't do anything to the current movie variable. Instead it returns the new string.
You are however better off changing the movie type from string to StringBuilder, which is a dynamically allocated buffer of characters, so your example becomes:
using System;
using System.Text;
using System.Collections.Generic;
namespace sotest
{
class Program
{
static void Main(string[] args)
{
Movies();
Console.ReadKey();
}
public static void Movies()
{
List<string> movieList = new List<string>();
bool check = false;
do
{
StringBuilder movie = new StringBuilder();
for (int i = 0; i < GetNum(); i++)
{
movie.Insert(0, Convert.ToString(GetLetter()));
}
movie.Insert(0, " ");
movie.Insert(0, Convert.ToString(GetYear()));
movie.Insert(0, " ");
for (int i = 0; i < GetNum(); i++)
{
movie.Insert(0, Convert.ToString(GetLetter()));
}
if (movieList.Contains(movie.ToString()))
{
check = false;
}
else
{
movieList.Add(movie.ToString());
check = true;
}
} while (check == false);
Console.WriteLine(movieList[0]);
}
public static Random _random = new Random();
public static char GetLetter()
{
int num = _random.Next(0, 26);
char let = (char)('a' + num);
return let;
}
public static int GetNum()
{
int num = _random.Next(4, 11);
return num;
}
public static int GetYear()
{
int num = _random.Next(1920, 2020);
return num;
}
}
}
The problem is that you are using movie.Insert incorrectly.
If you read the documentation for String.Insert it says
https://learn.microsoft.com/en-us/dotnet/api/system.string.insert?view=netframework-4.8
Returns a new string in which a specified string is inserted at a
specified index position in this instance
public string Insert (int startIndex, string value);
So it returns a new String, it does not amend the existing one. So you would need to do.
movie = movie.Insert(0, Convert.ToString(GetYear()));
However, I must also say that using String.Insert in this way is not the best approach.
You should instead look at using the StringBuilder class. It is very efficient when you want to amend strings (which are immutable objects).
You might want to read parts of this to help you understand. If you scroll down then it also suggests StringBuilder.
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/strings/
Insert() method is used to return a new string from the specified string at a specified index position. In your case, you are not capturing the updated string.
The best approach to solve this is through using StringBuilder object. Please note that StringBuilder object is much efficient rather than playing with immutable string.

How do I replace an array element within an if statement? C#

This is the second version of this code I've gone through as the first version ran too quickly for the Random function to work properly. I'm trying to make sure none of the randomly generated numbers are the same and if they are replace them in the array but it's not letting me call the array. Can someone tell me what I'm doing wrong?
using System;
using System.Timers;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp4
{
class Program
{
public static Timer aTimer;
static void Main(string[] args)
{
//Create three different random integers and store them
Random rnd = new Random();
int RandA = rnd.Next(0, 26);
int RandB = rnd.Next(0, 26);
int RandC = rnd.Next(0, 26);
//Turn those three variables into an array
int[] RandArray = { RandA, RandB, RandC };
//Make sure there are no duplicates
if (RandArray[0] == RandArray[1])
{
int RandArray[0] = rnd.Next(0, 26);
}
if (RandArray[1] == RandArray[2])
{
int RandArray[1] = rnd.Next(0, 26);
}
if (RandArray[2] == RandArray[0])
{
int RandArray[2] = rnd.Next(0, 26);
}
//Print out all three values seperately
for (int i = 0; i < 3; i++)
{
Console.WriteLine("Value of: {1}", i, RandArray[i]);
continue;
}
Console.ReadKey();
}
}
}
Well, I would potentially alter your approach.
public static class Randomizer
{
private static const generator = new Random();
public static int Generate(int minimum, int maximum) => generator.Next(minimum, maximum);
}
Then I would do the following:
public static class BuildRandom
{
public IEnumerable<int> FillCollection(int capacity)
{
for(int index = 0; index < capacity; index++)
yield return Randomizer.Generate(0, 26);
}
public static int GetRandomNumber() => Randomizer.Generate(0, 26);
}
Then I would simply do the following.
// Build Collection
var randomized = BuildRandom.FillCollection(5);
// Remove Duplicates
var filter = randomized.Distinct();
while(filter.Count != randomized.Count)
{
var value = BuildRandom.GetRandomNumber();
if(!filter.Any(number => number == value))
filter.Concat(new { value });
}
int RandArray[0] = is a syntax error. Try RandArray[0] =

C# Console App -- Trying to access a list from else statement

This is for a data structures and algorithms class. We're just starting out with bubble sort. The instructions were to generate random, unique integers and sort them using the sorting technique of the lecture. It will be required to add different sorting techniques as well.
To generate the list of random numbers, I generated a list and then shuffled the list using the fisher-yates algorithm. So I have my unique, sorted list of whatever size I choose.
I'm getting stuck because after I generate the random list, I am having problems accessing the list to run it through BubbleSort.
Is there any way I can do this?
class Algorithms
{
static void Main(string[] args)
{
string response = "";
//Main Console Menu
while (response != "exit")
{
Console.WriteLine("Type help for list of commands");
response = Console.ReadLine();
//List<int> toSort = new List<int>();
if (response.StartsWith("exit"))
{
Environment.Exit(0);
}
else if (response.ToLower().StartsWith("help"))
{
Help(response);
}
else if (response.ToLower().StartsWith("generate"))
{
// Shuffle(Generate(response));
// have been using the line above but adding next line for
//an idea of my problem
List<int> toSort = Shuffle(Generate(response));
}
else if (response.ToLower().StartsWith("bubble"))
{
//This doesn't work and I'm trying to figure out how it can
BubbleSort(toSort);
}
}
}
//Displays help information
public static void Help(string input)
{
Console.WriteLine("\ngenerate <integer> -- Generates a data set of intended amount of integers\n"+
"algorithm <algorithm type> -- Choose which algorithm to sort data\nexit -- exit application\n" );
}
//Generates List of integers from 0 to number choosen by user
public static List<int> Generate(string size)
{
int cutString = size.Length - 9;
string sizeSubset = size.Substring(9, cutString);
List<int> numGen = new List<int>();
int dataSetSize = Convert.ToInt32(sizeSubset);
for(int i = 0; i <= dataSetSize; i++)
{
numGen.Add(i);
// Console.WriteLine(numGen[i]);
}
return numGen;
}
//Use Fisher-Yates algorithm to shuffle the list.
static Random randomize = new Random();
public static List<int> Shuffle(List<int>makeRandom)
{
List<int> shuffled = new List<int>();
int n = makeRandom.Count;
while (n > 1)
{
n--;
int k = randomize.Next(n + 1);
int value = makeRandom[k];
makeRandom[k] = makeRandom[n];
makeRandom[n] = value;
shuffled.Add(value);
Console.WriteLine(value);
}
return shuffled;
}
public static void BubbleSort(List<int>input)
{
for(int i = 0; i <= input.Count; i++)
{
for (int j = 0; j <= (input.Count - 1); j++)
{
if (input[j] > input[j + 1])
{
int temp = input[j];
input[j] = input[j + 1];
input[j + 1] = temp;
Console.WriteLine("hello");
}
}
}
}
}
}
You defined list in scope of else if (response.ToLower().StartsWith("generate")) code block, so it is not accessible outside of that block. Move declaration to Main method scope, like this:
static void Main(string[] args)
{
string response = "";
//define your list here.
List<int> toSort = new List<int>();
//Main Console Menu
while (response != "exit")
{
Console.WriteLine("Type help for list of commands");
response = Console.ReadLine();
if (response.StartsWith("exit"))
{
Environment.Exit(0);
}
else if (response.ToLower().StartsWith("help"))
{
Help(response);
}
else if (response.ToLower().StartsWith("generate"))
{
toSort = Shuffle(Generate(response));
}
else if (response.ToLower().StartsWith("bubble"))
{
List<int> sortedList = BubbleSort(toSort);
}
}
}

Categories

Resources