I don't know whats wrong but i keep get the same outcome in console :
111
118
101
114
i solved that problem but now my console doesn't show me anything.
i updated my code!
this is my exercise:
Write a program and ask the user to continuously enter a number or type "Quit" to exit. The list of numbers may include duplicates. Display the unique numbers that the user has entered.
this is my code:
while (true)
{
var numbers = new List<int>();
Console.WriteLine("write a number or type quit if you want to exit, if you want to finish write over: ");
var input = Console.ReadLine();
if (input.ToLower() == "quit")
{
break;
}
if (input.ToLower() == "over")
{
var uniq = new List<int>();
foreach (var other in numbers)
{
Convert.ToInt32(other);
if (!uniq.Contains(other))
{
uniq.Add(other);
Convert.ToInt32(other);
Console.WriteLine(other);
continue;
}
int cifre;
if (int.TryParse(input, out cifre))
{
numbers.Add(cifre);
}
else
{
Console.WriteLine("Invalid input, type 'quit', 'over' or a numeric value");
}
}
}
}
thanks for helping.
I figured it out i just had to copy this line:
var numbers = new List();
to the top of while loop and use practicly everything the same i had at the bignning (because of the loop list wasnt sabving numbers in itself). i will edit my code so you can se rescued exercise.
Hope it helps someone
var numbers = new List<int>();
while (true)
{
Console.WriteLine("enter a number or quit or over");
var input = Console.ReadLine();
if (input == "quit")
{
break;
}
if (input == "over")
{
var uniq = new List<int>();
foreach (var value in numbers)
{
if (!uniq.Contains(value)) {
uniq.Add(value);
}
}
foreach (var numbr in uniq) {
Console.WriteLine(numbr);
}
}
else {
// inpout dodas v numbers
var conv = Convert.ToInt32(input);
numbers.Add(conv);
}
}
}
}
thanks for helping
Looks like there are some issues with the logic of the code. Here is the pseudo code I came up with to help you out:
While (true)
if (quit)
//end program
if (over)
//print out the list of integers
else
if (input is not a number)
continue
if (number is not in list)
//add to list
else
//do nothing
This should help you rewrite the program.
var numbers = new List<int>();
Console.WriteLine("Enter numbers or Quit");
while (true)
{
var value = Console.ReadLine();
if (value == "Quit")
{
break;
}
else
{
if (!numbers.Contains(Convert.ToInt32(value)))
numbers.Add(Convert.ToInt32(value));
}
}
foreach (var number in numbers)
{
Console.WriteLine(number);
}
Before you check whether the user has typed "over", you have already converted the characters in the input data and added them to the list. In other words, you're adding the ASCII character values of 'o', 'v', 'e', 'r' to the numeric list.
Move the "over" check and ensure they do not get added to the list:
while (true)
{
...input stuff
if (input.ToLower() == "quit")
{
break;
}
if (input.ToLower() == "over")
{
...make unique and report
continue;
}
foreach (var number in input)
{
var cifre = Convert.ToInt32(number);
numbers.Add(cifre);
}
}
This will solve your issue of having these same numbers in the list. You might also want to replace your foreach with:
int cifre;
if (int.TryParse(input, out cifre))
{
numbers.Add(cifre);
}
else
{
Console.WriteLine("Invalid input, type 'quit', 'over' or a numeric value");
}
Assuming you want to input a single numeric value each time.
Related
I´m having problems with getting my code to work while using TryParse to catch if the user where to input a string instead of a int. If I use it as it looks now I only get the base value of 0 if something other than an int is input. I want it to show an error message to the user.
Have tried messing around with a number of different ways of using TryParse but none of them has really been helpfull.
static void Main(string[] args)
{
Random r = new Random();
int speltal = r.Next(1,21);
bool play = false;
int myNum;
while (!play)
{
Console.Write("\n\tGuess a number between 1 and 20: ");
Int32.TryParse(Console.ReadLine(), out myNum);
if (myNum < guessNum)
{
Console.WriteLine("\tThe number you have guessed is to low");
Console.ReadLine();
}
if (myNum > guessNum)
{
Console.WriteLine("\tThe number you have guessed is to high");
Console.ReadLine();
}
if (myNum == guessNum)
{
Console.WriteLine("\tCongratulations you guessed the right number!");
Console.ReadLine();
}
I want it show an error message to the user if they put in anything other than a int. It also have to include TryParse according to my teatcher
You're not capturing the bool output of TryParse so you have no idea if a non-numeric value was entered. Try something like this:
bool isValid;
do
{
Console.Write("\n\tGuess a number between 1 and 20: ");
isValid = Int32.TryParse(Console.ReadLine(), out myNum);
if(!isValid)
{
Console.WriteLine("\n\tInvalid input detected. Please try again.");
}
} while(!isValid)
The TryParse method can only put integers in the passed variable (as it is of type int), so if the value passed to it can't be parsed into an integer, the default value of int (0) will be assigned to the variable.
The way TryParse tell you if it successfully parsed the number or not, is by returning a boolean indicator.
You can try this:
while (true)
{
bool valid = int.TryParse(Console.ReadLine(), out myNum);
if(valid)
break;
Console.WriteLine("Input invalid. Please try again");
}
TryParse returns a Boolean which indicates if the input string was successfully parsed or not. Both of the answers above are correct on how to handle a invalid input but, here is a cleaner version which will also uphold the rule, between 1 and 20:
while (true)
{
Console.Write("\n\tGuess a number between 1 and 20: ");
//Checks to see if the input was successfully parsed to a integer also, performs a Trim on the input as to remove any accidental white spaces that a user might have typed in, e.g. "1000 "
if (int.TryParse(Console.ReadLine().Trim(), out myNum))
{
//Checks to see if the parsed number is in the specified range
if ((myNum > 0) && (myNum < 21))
{
break;
}
Console.WriteLine("\tThe input number was out of the specified range.");
}
else
{
Console.WriteLine("\tFailed to parse the input text.");
}
//Optional, makes the thread sleep so the user has the time to read the error message.
Thread.Sleep(1500);
//Optional, clears the console as to not create duplicates of the error message and the value of Console.Write
Console.Clear();
}
// Continue here, if (myNum < guessNum) . . .
You should use the bool returned by TryParse. Something that looks like this:
Updated answer:
static void Main(string[] args)
{
Random random = new Random();
int guessNum = random.Next(1, 21);
while(true)
{
Console.WriteLine("Guess the number between 1 and 21.");
if (Int32.TryParse(Console.ReadLine(), out int input))
{
if (input == guessNum)
{
Console.WriteLine($"You guessed it right. The number is {input}");
if(ShouldContinue())
{
guessNum = random.Next();
continue;
}
else
{
break;
}
}
if (input < guessNum)
Console.WriteLine("The number you guessed is smaller.");
else
Console.WriteLine("The number you guessed is bigger");
}
else
{
Console.WriteLine("Please enter a number between 1 and 21 as your guess");
}
}
}
static bool ShouldContinue()
{
while (true)
{
Console.WriteLine($"Do you want to continue playing? (y/n)");
string continueInput = Console.ReadLine().Trim().ToLower();
if (continueInput == "y")
return true;
else if (continueInput == "n")
return false;
else
Console.WriteLine("Invalid input!. Please choose 'y' or 'n'.");
}
}
Old answer:
while (true)
{
if (Int32.TryParse(inputInt, out int myNum))
{
// your logic goes here, too low/high or correct answer.
}
}
I do not understand why this code prints the contents of the array twice.
static void Main(string[] args)
{
Int64 userlength;
Int64 userlengthcounter;
String unencrypted;
char current;
start:
Console.WriteLine("Please enter how many characters the string you want encrypyted to be:");
userlength = Convert.ToInt64(Console.ReadLine());
Console.WriteLine("Please enter the string you want to be encrypted:");
unencrypted = Console.ReadLine();
int[] first = new int[userlength];
int[] second = new int[userlength];
if (userlength != unencrypted.Length)
{
Console.WriteLine("The string you entered was not the same length as the number of characters you specified");
goto start;
}
for (int i = 0; i < userlength; i++)
{
Console.WriteLine(unencrypted[i]);
current = unencrypted[i];
first[i] = current;
}
foreach (char item in first)
{
Console.WriteLine(item.ToString());
}
Console.ReadLine();
}
For example entering abcd would return abcdabcd and i don't understand why. Any help would be appreciated thanks.
It's because you have two loops, first you print each character in unencrypted in the for loop and store the chars in first array.
Then you loop over the array and print the chars again with foreach.
Additional Note: Using goto is almost always a bad idea because it makes your code hard to follow and unreadable. Because you have to manually track where the code jumps.
You can do the same thing with a do-while loop instead.
do {
Console.WriteLine("Please enter how many characters the string you want encrypyted to be:");
userlength = Convert.ToInt64(Console.ReadLine());
Console.WriteLine("Please enter the string you want to be encrypted:");
unencrypted = Console.ReadLine();
int[] first = new int[userlength];
int[] second = new int[userlength];
if (userlength != unencrypted.Length)
{
Console.WriteLine("The string you entered was not the same length as the number of characters you specified");
}
} while(userlength != unencrypted.Length);
you specifically build "first" then you print it in foreach, basically displaying the same content twice:
for (int i = 0; i < userlength; i++)
{
Console.WriteLine(unencrypted[i]);
current = unencrypted[i];
first[i] = current;
}
foreach (char item in first)
{
Console.WriteLine(item.ToString());
}
I need to modify this for a comma-separated string. I want the user to be able to enter multiple numbers but I need to validate they are all numbers before I continue. Any thoughts?
while (!int.TryParse(Console.ReadLine(), out iValue))
{
Console.WriteLine("Please Enter a valid Number!");
}
You can just implemenent custom method for parsing integer arrays and use it in the same way:
void Main()
{
while (!TryParseIntegerArray(Console.ReadLine(), out var arr))
{
Console.WriteLine("Please Enter a valid integer or comma-separated string!");
}
// work with arr here
}
bool TryParseIntegerArray(string input, out int[] arr)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
try
{
arr = input.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToArray();
return true;
}
catch (FormatException)
{
arr = null;
return false;
}
}
However, I wouldn't recomment using Console.ReadLine() directly as an argument, either for TryParseIntegerArray and int.TryParse. You need to check it for null, at least. For example:
string input;
int[] arr;
do
{
input = Console.ReadLine();
if (string.IsNullOrWhiteSpace(input))
{
Console.WriteLine($"Good bye!");
return;
}
} while (!TryParseIntegerArray(input, out arr));
What I ended up with
while (true)
{
try
{
var entry = Console.ReadLine();
List<int> myNumbers = entry.Split(',').Select(int.Parse).ToList();
serializedValue = _unitOfWork.GetSerializedCollection(myNumbers);
Console.WriteLine(serializedValue);
Console.ReadLine();
}
catch (FormatException)
{
Console.Write("You must enter a number.");
continue;
}
break;
}
I need some help with a C# program that i am creating. So in this scenario i am inputting duplicate values into the program. For Example, a,b,b,c,c.
The exercise is that if there are any duplicated letters inputted (no numbers) i should get an error stating "Duplicate Value. Please Try Again!" and will not accept the duplicate value, and should show the values as a,b,c,d,e.
class Program
{
static void Main(string[] args)
{
char[] arr = new char[5];
//User input
Console.WriteLine("Please Enter 5 Letters only: ");
for (int i = 0; i < arr.Length; i++)
{
arr[i] = Convert.ToChar(Console.ReadLine());
}
//display
for(int i = 0; i<arr.Length; i++)
{
Console.WriteLine("You have entered the following inputs: ");
Console.WriteLine(arrArray[i]);
}
}
}
Choose right data structure at beginning, use HashSet instead of array since the operations are mainly looking up & inserting.
Using a hashtable (Generic Dictionary) is an efficient way to determine if an entered character has already been encountered.
Also, the Char.IsLetter method in the .NET framework is a great way to check for bad data.
static void Main(string[] args) {
Dictionary<char, bool> charsEntered = new Dictionary<char, bool>();
Console.WriteLine("Please enter 5 characters, each on a separate line.");
while (charsEntered.Count() < 5) {
Console.WriteLine("Enter a character:");
char[] resultChars = Console.ReadLine().ToCharArray();
if(resultChars.Length != 1 || !Char.IsLetter(resultChars[0])) {
Console.WriteLine("Bad Entry. Try again.");
} else {
char charEntered = resultChars[0];
if (charsEntered.ContainsKey(charEntered))
Console.WriteLine("Character already encountered. Try again.");
else
charsEntered[charEntered] = true;
}
}
Console.WriteLine("The following inputs were entered:");
Console.WriteLine(String.Join(", ", charsEntered.Keys));
Console.ReadLine();
}
Use Any linq expression to validate duplicates. char.TryParse will validates input and returns true when succeeded.
public static void Main()
{
char[] arr = new char[5];
//User input
Console.WriteLine("Please Enter 5 Letters only: ");
for (int i = 0; i < arr.Length; i++)
{
char input;
if(char.TryParse(Console.ReadLine(), out input) && !arr.Any(c=>c == input))
{
arr[i] = input;
}
else
{
Console.WriteLine( "Error : Either invalid input or a duplicate entry.");
i--;
}
}
Console.WriteLine("You have entered the following inputs: ");
//display
for(int i = 0; i<arr.Length; i++)
{
Console.WriteLine(arr[i]);
}
}
Working Code
Elaborating on Shelvin's answer of using HashSet
HashSet<char> chars = new HashSet<char>();
//User input
Console.WriteLine("Please Enter 5 Letters only: ");
for (int i = 0; i < 5; )
{
char c = Convert.ToChar(Console.ReadLine());
if(!("abcdefghijklmnopqrstuvwxyz".Contains(c.ToString().ToLower())))
{
Console.WriteLine("Please enter an alphabet");
continue;
}
else if (!chars.Contains(c))
{
chars.Add(c);
i++;
}
else
{
Console.WriteLine("Duplicate value please try again");
continue;
}
}
//display
Console.WriteLine("You have entered the following inputs: ");
foreach(char c in chars)
Console.WriteLine(c.ToString());
Console.Read();
Keep it simple, and although a HashSet is nice semantically, it's not needed for 5 elements (it's actually slower than a List in that case). Worse, it requires a parallel structure to track the characters (assuming you care about order).
Clearly none of these considerations matter for such a small example but it's good to learn them up front and don't always jump to big-O notation when actually measured performance and memory consumption should be your guide for most practical applications.
Instead you can simply do:-
List<char> chars = new List<char>(5);
while (chars.Count < 5)
{
char c = Console.ReadKey().KeyChar;
if (!char.IsLetter(c)) continue;
if (chars.Contains(char)) continue;
chars.Add(char);
}
Plus whatever error messages you want to add.
I want to add multiple values into an array, but I want to stop when I feel like it.
Here is the condition I added
while (numbers[i] != 10)
{
i++;
numbers[i] = int.Parse(Console.ReadLine());
Console.WriteLine(numbers[i]);
}
It will stop when the value entered is 10. But I want it to stop when I just press ENTER.
How do I do this?
If you are asking about how to detect the "just press ENTER" condition:
var input = Console.ReadLine();
if (input == "") {
break;
}
numbers[i] = int.Parse(input);
// etc
var numbers = new List<int>();
string s;
while(!string.IsNullOrEmpty(s = Console.ReadLine())) {
numbers.Add(int.Parse(s));
}
I guess you are looking for some way to re-size the array, you can use Array.Resize
Declare numbers like this.
List<int> numbers = new List<int>();
Then modify the loop as such.
while (numbers[i] != 10)
{
i++;
string input = Console.ReadLine();
if (string.IsNullOrEmpty(input)) { break; }
numbers.Add(int.Parse(input));
Console.WriteLine(numbers[i]);
}