So essentially I want the displayToPlayer variable have the spaces automatically added but I'm not quite sure how to achieve this.
How can I have the spaces automatically added to the hidden message without using a turn or it been added to the guessed letter tally.
Current Result:
Desired Result:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace guessingGame
{
class Program
{
static void Main(string[] args)
{
string[] quoteList = {
"NEVER GUNNA LET YOU DOWN",
/*"NEVER GUNNA RUN AROUND",
"THIS IS A TEST"*/
}; // the list of quotes that need to be guessed by the player
Random random = new Random((int)DateTime.Now.Ticks);
string quoteToGuess = quoteList[random.Next(0, quoteList.Length)];
string quoteToGuessUppercase = quoteToGuess.ToUpper();
StringBuilder displayToPlayer = new StringBuilder(quoteToGuess.Length);
for (int i = 0; i < quoteToGuess.Length; i++)
{
displayToPlayer.Append('*');
}
List<char> correctGuesses = new List<char>();
List<char> incorrectGuesses = new List<char>();
int quoteToGuessLength = quoteToGuess.Count(characters => !Char.IsWhiteSpace(characters));
int turnsLeft = quoteToGuess.Distinct().Count(characters => !Char.IsWhiteSpace(characters)) + 3;
bool quoteGuessed = false;
int lettersRevealed = 0;
string userInput;
char userGuess;
Console.WriteLine("Can you work out the quote? (you have {0} chances)", turnsLeft);
Console.WriteLine();
Console.WriteLine();
Console.WriteLine(displayToPlayer.ToString());
Console.WriteLine();
while (!quoteGuessed && turnsLeft > 0)
{
Console.Write("Enter your letter ==>");
try
{
userInput = Console.ReadLine().ToUpper();
userGuess = userInput[0];
if (correctGuesses.Contains(userGuess))
{
Console.WriteLine("You've already tried '{0}', and it was correct!", userGuess);
continue;
}
else if (incorrectGuesses.Contains(userGuess))
{
Console.WriteLine("You've already tried '{0}', and it was wrong!", userGuess);
continue;
}
if (quoteToGuessUppercase.Contains(userGuess))
{
correctGuesses.Add(userGuess);
for (int i = 0; i < quoteToGuess.Length; i++)
{
if (quoteToGuessUppercase[i] == userGuess)
{
displayToPlayer[i] = quoteToGuess[i];
lettersRevealed++;
}
}
if (lettersRevealed == quoteToGuess.Length)
{
quoteGuessed = true;
}
turnsLeft--;
Console.Clear();
Console.WriteLine("You have guessed {0} letter(s) out of a total of {1}", lettersRevealed, quoteToGuessLength);
Console.WriteLine("You have {0} attempts remaining!", turnsLeft);
Console.WriteLine();
Console.WriteLine(displayToPlayer.ToString());
Console.WriteLine();
Console.WriteLine("Correct guess, there's a '{0}' in it!", userGuess);
Console.WriteLine();
}
else
{
incorrectGuesses.Add(userGuess);
turnsLeft--;
Console.Clear();
Console.WriteLine("You have guessed {0} letter(s) out of a total of {1}", lettersRevealed, quoteToGuessLength);
Console.WriteLine("You have {0} attempts remaining!", turnsLeft);
Console.WriteLine();
Console.WriteLine(displayToPlayer.ToString());
Console.WriteLine();
Console.WriteLine("Incorrect guess, there's no '{0}' in it!", userGuess);
Console.WriteLine();
}
}
catch (Exception e)
{
Console.WriteLine("Enter A Valid Character");
}
}
if (quoteGuessed)
{
Console.WriteLine(quoteToGuess);
Console.WriteLine("You have guessed all {0} letters out of a total of {0} Well done!!!", quoteToGuessLength);
}
else
{
Console.WriteLine("You lost! It was '{0}'", quoteToGuess);
}
}
}
}
If i understand you correctly, this will probably work
for (int i = 0; i < quoteToGuess.Length; i++)
{
displayToPlayer.Append(quoteToGuess[i] == ' ' ? ' ' : '*');
}
Its basically saying, if the character at the index of i in quoteToGuess is ' ', then add ' ', if not add '*'
?: Operator (C# Reference)
The conditional operator (?:), commonly known as the ternary
conditional operator, returns one of two values depending on the value
of a Boolean expression. Following is the syntax for the conditional
operator.
Strings and indexes
An index is the position of a Char object (not a Unicode character) in
a String. An index is a zero-based, nonnegative number that starts
from the first position in the string, which is index position zero
You can get rid of the StringBuilder and your for loop completely using System.Linq:
var displayToPlayer = new string(quoteToGuess.Select(c => c == ' ' ? ' ' : '*').ToArray());
If you get an error because Select() doesn't seem to be defined, add this on top of your file:
using System.Linq;
Related
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();
}
I am making a program for a hangman game that picks a random word from a text file of words and then asks the user to guess each letter of the word. Each letter in the word is displayed with an asterisk and when the user makes a correct guess the actual letter is then displayed. After the word is guessed it will then display the number of times missed and ask the user if they want to guess another word.
I have the asterisks hard coded but I would like the asterisks to be the same length of the random word chosen from the text file. I am not sure how I would do this
Any help would be appreciated.
static void Main(string[] args)
{
char[] guessed = new char[26];
char[] testword = "******".ToCharArray();
char[] word = RandomLine().ToCharArray();
char[] copy = word;
char guess;
char playAgain;
int amountMissed = 0, index = 0;
Console.WriteLine(testword);
do
{
Console.WriteLine("I have picked a random word on animals");
Console.WriteLine("Your task is to guess the correct word");
while (testword != word)
{
Console.Write("Please enter a letter to guess: ");
guess = char.Parse(Console.ReadLine());
bool right = false;
for (int j = 0; j < copy.Length; j++)
{
if (copy[j] == guess)
{
Console.WriteLine("Your guess is correct.");
testword[j] = guess;
guessed[index] = guess;
index++;
right = true;
}
}
if (right != true)
{
Console.WriteLine("Your guess is incorrect.");
amountMissed++;
}
else
{
right = false;
}
Console.WriteLine(testword);
}
Console.WriteLine($"The word is {copy}. You missed {amountMissed} times.");
Console.WriteLine("Do you want to guess another word? Enter y or n: ");
playAgain = char.Parse(Console.ReadLine());
} while (playAgain == 'y' || playAgain == 'Y');
Console.WriteLine("Good-Bye and thanks for playing my Hangman game.");
}
public static string RandomLine()
{
try
{
// store text file in an array and return a random value
string[] lines = File.ReadAllLines("C:\\Intel\\Advanced1.csv");
Random rand = new Random();
return lines[rand.Next(lines.Length)];
}
catch (Exception e)
{
Console.WriteLine("The file could not be read");
Console.WriteLine(e.Message);
}
}
To display the coded word (with asterisks) with same length as word, you could use
char[] testword = new string('*',word.Length).ToCharArray();
Making few other corrections in your code
char[] guessed = new char[26];
char guess;
char playAgain;
int amountMissed = 0, index = 0;
do
{
char[] word = RandomLine().ToCharArray(); // Change :This needs to be inside the loop so that new random word could be selected user selects to continue the game
char[] testword = new string('*',word.Length).ToCharArray(); // Change : Reordered initilization of word and testword so that we could generate testword with same length as original
char[] copy = word;
Console.WriteLine(testword);
Console.WriteLine("I have picked a random word on animals");
Console.WriteLine("Your task is to guess the correct word");
while (!testword.SequenceEqual(word)) // Change : Comparison of arrays
{
Console.Write("Please enter a letter to guess: ");
guess = char.Parse(Console.ReadLine());
bool right = false;
for (int j = 0; j < copy.Length; j++)
{
if (copy[j] == guess)
{
Console.WriteLine("Your guess is correct.");
testword[j] = guess;
guessed[index] = guess;
index++;
right = true;
}
}
if (right != true)
{
Console.WriteLine("Your guess is incorrect.");
amountMissed++;
}
else
{
right = false;
}
Console.WriteLine(testword);
}
Console.WriteLine($"The word is {copy}. You missed {amountMissed} times.");
Console.WriteLine("Do you want to guess another word? Enter y or n: ");
playAgain = char.Parse(Console.ReadLine());
} while (playAgain == 'y' || playAgain == 'Y');
Console.WriteLine("Good-Bye and thanks for playing my Hangman game.");
This way:
class Program
{
static void Main(string[] args)
{
bool found = false;
string originalWord = "test";
char[] word = originalWord.ToCharArray();
char[] asteriskedWord = new string('*', word.Length).ToCharArray();
while (found == false)
{
Console.WriteLine(asteriskedWord);
string input = Console.ReadLine();
if (input.Length != 1)
{
Console.WriteLine("Your input can be only one char.");
}
else
{
char c = char.Parse(input);
for (int i = 0; i < word.Length; i++)
{
if (word[i] == c)
{
asteriskedWord[i] = c;
word[i] = '*';
int missingCharsAmount = asteriskedWord.Count(x => x == '*');
Console.WriteLine("Correct, missing " + missingCharsAmount + " chars.");
if (missingCharsAmount == 0)
{
found = true;
}
break;
}
}
}
}
}
}
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);
}
I am learning c#, and have home works to make simple dictionary in console aplication.
I wrote all the code and it should work good but in one of the for loops the program throws Error:System.IndexOutofRange.
I tried all I know (I am only beginner so I dont know much) but it always gives the error.
The main idea of the program is the user must enter how much words he wishes to use then enter the words in the his language (my is Hebrew so in the program is Hebrew) and in English and it save the words in two deffernt Arrays but in same index. Then the program ask the user to enter sentence in his language and then the program runs on the sentence finds the words (each time the program see space it starts a new word), then with another for loop it looks in the Hebrew Array and if it finds match place the word that in the same index but in the English Array, and if not found it writes the original word.
static void Main(string[] args)
{
Console.WriteLine("Enter the number of words you wish to use");
int wordsNumber = int.Parse(Console.ReadLine());
string[] hebrew = new string[wordsNumber];
string[] english = new string[wordsNumber];
for (int i = 0; i < wordsNumber; i++)
{
Console.WriteLine("Enter word in Hebrew.");
hebrew[i] = Console.ReadLine();
Console.WriteLine("Now enter the translate of {0} in English.",hebrew[i]);
english[i] = Console.ReadLine();
}
Console.WriteLine("Now enter the sentence that you want to translate..and press ENTER");
string searchSentence = Console.ReadLine();
string translateWord = "";
string result = "";
while(searchSentence != "stop")
{
for (int i = 0; i < searchSentence.Length;i++ )
{
translateWord = "";
while ((searchSentence[i] == ' ')&&(searchSentence.Length > i))//Skip the spaces in the start of the sentence
i++;
while ((searchSentence[i] != ' ') && (searchSentence.Length > i))//Here is the problem when with the OutOfRnge
{
translateWord += searchSentence[i];
i++;
}
for(int j = 0;j<hebrew.Length ;j++)
{
if (translateWord == hebrew[j])
{
result += english[j];
}
else
{
result += translateWord[i];
}
result += " ";
}
}
Console.WriteLine(result);
Console.WriteLine("Enter new sentence for translate or enter 'stop' to EXIT the programm");
searchSentence = Console.ReadLine();
}
while ((searchSentence[i] != ' ') && (searchSentence.Length > i))
Consider that the way you are used to read (right-to-left in your neck of the woods) is affecting the way you write code. This code is backwards, both in the order of the && operands and in the Length test. And thus doesn't take advantage of the short-circuiting behavior of the && operator. Probably difficult to unlearn, something you'll have to work on.
Avoid this exception with:
while ((i < searchSentence.Length) && (searchSentence[i] != ' '))
Which ensures that searchSentence[i] cannot throw the IndexOutOfRangeException.
Your code was very confusing and it would be hard to tell where the error was.. However you would be better off constructing a dictionary full of translations and then using that. I have left out error handling for you to expand upon but here is an example of doing the exact same - but with a dictionary
Dictionary<string, string> words = new Dictionary<string, string>();
Console.WriteLine("Enter the number of words you wish to use");
int wordsNumber = int.Parse(Console.ReadLine());
for (int i = 0; i < wordsNumber; i++)
{
Console.WriteLine("Enter word in Hebrew.");
string hebrew = Console.ReadLine();
Console.WriteLine("Now enter the translate of {0} in English.", hebrew);
string english = Console.ReadLine();
words.Add(hebrew, english);
}
Console.WriteLine("Now enter the sentence that you want to translate..and press ENTER");
string searchSentence = Console.ReadLine();
string[] splitSentence = searchSentence.Split(new char[]{' '});
string result = "";
foreach (string s in splitSentence)
result += string.Format("{0} ", words[s]);
Console.WriteLine(result);
Console.ReadLine();
Looking at
while(searchSentence != "stop")
{
for (int i = 0; i < searchSentence.Length;i++ )
{
translateWord = "";
while ((searchSentence[i] == ' ')&&(searchSentence.Length > i))//Skip the spaces in the start of the sentence
i++; //updated here and used on nex line when i could be greater than SearchSentence.Length now
while ((searchSentence[i] != ' ') && (searchSentence.Length > i))//Here is the problem when with the OutOfRnge
{
translateWord += searchSentence[i];
i++; // updated here
}
for(int j = 0;j<hebrew.Length ;j++)
{
if (translateWord == hebrew[j])
{
result += english[j];
}
else
{
result += translateWord[i];
}
result += " ";
}
}
You increment i inside the for loop. If it becomes equal to or greater than searchSentence.Length then you use it it will throw the error you get
edit to fix make this change from this
for (int i = 0; i < searchSentence.Length;i++ )
{
translateWord = "";
while ((searchSentence[i] == ' ')&&(searchSentence.Length > i))//Skip the spaces in the start of the sentence
i++;
while ((searchSentence[i] != ' ') && (searchSentence.Length > i))//Here is the problem when with the OutOfRnge
{
translateWord += searchSentence[i];
i++;
}
for(int j = 0;j<hebrew.Length ;j++)
{
if (translateWord == hebrew[j])
{
result += english[j];
}
else
{
result += translateWord[i];
}
result += " ";
}
}
to this
for (int i = 0; i < searchSentence.Length;i++ )
{
if(((searchSentence[i] != ' ')&&(searchSentence.Length > i)))
{
while ((searchSentence[i] != ' ') && (searchSentence.Length > i))//Here was the problem when with the OutOfRnge
{
translateWord += searchSentence[i];
i++; // updated here
if(i>=searchSentence.Length)
{
break;
}
}
if(i>=searchSentence.Length)
for(int j = 0;j<hebrew.Length ;j++)
{
if (translateWord == hebrew[j])
{
result += english[j];
}
else
{
result += translateWord[i];
}
result += " ";
}
}
}
i know how to make a console read two integers but each integer by it self like this
int a = int.Parse(Console.ReadLine());
int b = int.Parse(Console.ReadLine());
if i entered two numbers, i.e (1 2), the value (1 2), cant be parse to integers
what i want is if i entered 1 2 then it will take it as two integers
One option would be to accept a single line of input as a string and then process it.
For example:
//Read line, and split it by whitespace into an array of strings
string[] tokens = Console.ReadLine().Split();
//Parse element 0
int a = int.Parse(tokens[0]);
//Parse element 1
int b = int.Parse(tokens[1]);
One issue with this approach is that it will fail (by throwing an IndexOutOfRangeException/ FormatException) if the user does not enter the text in the expected format. If this is possible, you will have to validate the input.
For example, with regular expressions:
string line = Console.ReadLine();
// If the line consists of a sequence of digits, followed by whitespaces,
// followed by another sequence of digits (doesn't handle overflows)
if(new Regex(#"^\d+\s+\d+$").IsMatch(line))
{
... // Valid: process input
}
else
{
... // Invalid input
}
Alternatively:
Verify that the input splits into exactly 2 strings.
Use int.TryParse to attempt to parse the strings into numbers.
You need something like (no error-checking code)
var ints = Console
.ReadLine()
.Split()
.Select(int.Parse);
This reads a line, splits on whitespace and parses the split strings as integers. Of course in reality you would want to check if the entered strings are in fact valid integers (int.TryParse).
Then you should first store it in a string and then split it using the space as token.
Read the line into a string, split the string, and then parse the elements. A simple version (which needs to have error checking added to it) would be:
string s = Console.ReadLine();
string[] values = s.Split(' ');
int a = int.Parse(values[0]);
int b = int.Parse(values[1]);
string[] values = Console.ReadLine().Split(' ');
int x = int.Parse(values[0]);
int y = int.Parse(values[1]);
in 1 line, thanks to LinQ and regular expression (no type-checking neeeded)
var numbers = from Match number in new Regex(#"\d+").Matches(Console.ReadLine())
select int.Parse(number.Value);
string x;
int m;
int n;
Console.WriteLine("Enter two no's seperated by space: ");
x = Console.ReadLine();
m = Convert.ToInt32(x.Split(' ')[0]);
n = Convert.ToInt32(x.Split(' ')[1]);
Console.WriteLine("" + m + " " + n);
This Should work as per your need!
public static class ConsoleInput
{
public static IEnumerable<int> ReadInts()
{
return SplitInput(Console.ReadLine()).Select(int.Parse);
}
private static IEnumerable<string> SplitInput(string input)
{
return Regex.Split(input, #"\s+")
.Where(x => !string.IsNullOrWhiteSpace(x));
}
}
int a, b;
string line = Console.ReadLine();
string[] numbers= line.Split(' ');
a = int.Parse(numbers[0]);
b = int.Parse(numbers[1]);
Try this:
string numbers= Console.ReadLine();
string[] myNumbers = numbers.Split(' ');
int[] myInts = new int[myNumbers.Length];
for (int i = 0; i<myInts.Length; i++)
{
string myString=myNumbers[i].Trim();
myInts[i] = int.Parse(myString);
}
Hope it helps:)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SortInSubSet
{
class Program
{
static int N, K;
static Dictionary<int, int> dicElements = new Dictionary<int, int>();
static void Main(string[] args)
{
while (!ReadNK())
{
Console.WriteLine("***************** PLEASE RETRY*********************");
}
var sortedDict = from entry in dicElements orderby entry.Key/3 , entry.Value ascending select entry.Value;
foreach (int ele in sortedDict)
{
Console.Write(ele.ToString() + " ");
}
Console.ReadKey();
}
static bool ReadNK()
{
dicElements = new Dictionary<int, int>();
Console.WriteLine("Please entere the No. of element 'N' ( Between 2 and 9999) and Subset Size 'K' Separated by space.");
string[] NK = Console.ReadLine().Split();
if (NK.Length != 2)
{
Console.WriteLine("Please enter N and K values correctly.");
return false;
}
if (int.TryParse(NK[0], out N))
{
if (N < 2 || N > 9999)
{
Console.WriteLine("Value of 'N' Should be Between 2 and 9999.");
return false;
}
}
else
{
Console.WriteLine("Invalid number: Value of 'N' Should be greater than 1 and lessthan 10000.");
return false;
}
if (int.TryParse(NK[1], out K))
{
Console.WriteLine("Enter all elements Separated by space.");
string[] kElements = Console.ReadLine().Split();
for (int i = 0; i < kElements.Length; i++)
{
int ele;
if (int.TryParse(kElements[i], out ele))
{
if (ele < -99999 || ele > 99999)
{
Console.WriteLine("Invalid Range( " + kElements[i] + "): Element value should be Between -99999 and 99999.");
return false;
}
dicElements.Add(i, ele);
}
else
{
Console.WriteLine("Invalid number( " + kElements[i] + "): Element value should be Between -99999 and 99999.");
return false;
}
}
}
else
{
Console.WriteLine(" Invalid number ,Value of 'K'.");
return false;
}
return true;
}
}
}
I have a much simpler solution, use a switch statement and write a message for the user in each case, using the Console.write() starting with a ("\n").
Here's an example of filling out an array with a for loop while taking user input. * Note: that you don't need to write a for loop for this to work*
Try this example with an integer array called arrayOfNumbers[] and a temp integer variable. Run this code in a separate console application and Watch how you can take user input on the same line!
int temp=0;
int[] arrayOfNumbers = new int[5];
for (int i = 0; i < arrayOfNumbers.Length; i++)
{
switch (i + 1)
{
case 1:
Console.Write("\nEnter First number: ");
//notice the "\n" at the start of the string
break;
case 2:
Console.Write("\nEnter Second number: ");
break;
case 3:
Console.Write("\nEnter Third number: ");
break;
case 4:
Console.Write("\nEnter Fourth number: ");
break;
case 5:
Console.Write("\nEnter Fifth number: ");
break;
} // end of switch
temp = Int32.Parse(Console.ReadLine()); // convert
arrayOfNumbers[i] = temp; // filling the array
}// end of for loop
The magic trick here is that you're fooling the console application, the secret is that you're taking user input on the same line you're writing your prompt message on. (message=>"Enter First Number: ")
This makes user input look like is being inserted on the same line. I admit it's a bit primitive but it does what you need without having to waste your time with complicated code for a such a simple task.