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]);
}
Related
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.
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.
My question is how to output things in the array in reverse order
grouped by two things with resorting only to the while-loop
(i.e., without for-loop and Reverse method, etc.)
I know that the second while-loop is not correct but I do not know how to modify it.
Thank you in advance for your suggestions.
Console.WriteLine("Please type four things.");
const int MAX_SIZE = 4;
string[] things = new string[MAX_SIZE];
int i = 0;
while (i < MAX_SIZE)
{
Console.WriteLine("Please type the things.");
things[i] = Console.ReadLine();
i++;
}
i = 0;
while (i < MAX_SIZE)
{
Console.Write(things[i] + ", ");
i--;
}
Try
i = MAX_SIZE - 1
while (i >= 0)
{
Console.Write(things[i] + ", ");
i--;
}
The reason I am using MAX_SIZE-1 is because arrays in C# are 0-based. The first element will always be in position 0. If the array has 4 elements, the final element will be in position 3.
If you want to print things in twos, you can just do the following:
i = MAX_SIZE - 1
while (i >= 0)
{
Console.Write(things[i-1] + ", " things[i]);
i -= 2;
}
Is there any reason you want to use a while loop instead of a for loop?
for(var i=0;i<MAX_SIZE;i++) {
Console.WriteLine("Please type the things.");
things[i] = Console.ReadLine();
i++;
}
for(var i=MAX_SIZE-1;i>=0;i--){
Console.Write(things[i] + ", ");
}
If I understand the task correctly, next code should work for you:
int i = things.Length - 1;
while(i > 0)
{
Console.Write("({0}, {1}) ", things[i], things[i - 1]);
i -= 2;
}
//in case the the list lenght is odd, output the last element without pair
if(i == 0)
{
Console.Write("({0})", things[i]);
}
if statement can be omitted if things list length is always even because it is required only if you need to pring the last (the first in things list) element, which has no pair.
I'm new to C# and programming as a whole and i have a quick question to ask you guys, I've searched a bit but only found far too complicated examples for me to implement in my work so here goes:
int[] newArray = new int[7];
Console.WriteLine("Hello! Please enter 7 numbers between 1-25, press ENTER after each number. ");
for (int i = 0; i < newArray.Length; i++)
bool loop = true;
do
{
try
{
newArray[i] = Convert.ToInt32(Console.ReadLine());
loop = false;
}
catch
{
Console.WriteLine("You may only enter numbers!");
}
} while (loop);
Console.Write("You entered the following numbers: ");
for (int i = 0; i < newArray.Length; i++)
{
Console.WriteLine(newArray[i]);
}
}
This is the first part of a bingogame im trying to write, but i can't understand why the names loop and i don't exist, should i make something static? Move some brackets around? Please help.
You need to wrap the entire for statement in braces, otherwise it will only execute the next line of code, which is just bool loop = true;.
for (int i = 0; i < newArray.Length; i++)
{ // <-- Add this
bool loop = true;
do
{
try
{
newArray[i] = Convert.ToInt32(Console.ReadLine());
loop = false;
}
catch
{
Console.WriteLine("You may only enter numbers!");
}
} while (loop);
Console.Write("You entered the following numbers: ");
}
It's worth to mention about string.Join method to print all elements of the list.
Console.WriteLine("You entered the following numbers: ");
Console.WriteLine(string.Join(", ", newArray));
After using Parse/TryParse method, you don't need to use Convert.ToInt32 any more.
To validate number and be able to reenter it, it is much better to do 2 IF statements instead of using Constains method of Enumerable class.
while (!int.TryParse(Console.ReadLine(), out number) || number < 1 || number > 25)
{
Console.WriteLine("You may only enter numbers from range 1-25!");
}
Make one single bracket right after your for cycle.
You're missing an open brace. This looks like homework so I'm not going to rewrite it for you. Take a closer look and work on the formatting and indentations. That will give you a clue as to were that missing brace should be.
Here is a nicer way to test for number input without the try/catch
var newArray = new int[7];
Console.WriteLine("Hello! Please enter 7 numbers between 1-25, press ENTER after each number. ");
for (var i = 0; i <= newArray.Length - 1; i++)
{
int number;
while (!int.TryParse(Console.ReadLine(), out number))
{
Console.WriteLine("You may only enter numbers!");
}
newArray[i] = Convert.ToInt32(number);
}
Console.WriteLine("You entered the following numbers: ");
foreach (var t in newArray)
{
Console.WriteLine(t);
}
I'm working on an application that has the user choose how many integers to enter into an array, and then has them input the numbers to be added to the array. After each number is inputted, it shows all non-duplicate integers entered by the user up to that point in a vertical list. If it isn't unique, it informs the user that it has already been inputted.
I'm not sure how to make the application list every integer entered, rather than just the most recent one.
Here's my code:
static void Main(string[] args)
{
//checks how many numbers will be entered
int manyNumbers;
Console.WriteLine("How many numbers will you enter?");
manyNumbers = Convert.ToInt32(Console.ReadLine());
int[] array = new int[manyNumbers];
//starts asking for numbers
for (int i = 0; i < manyNumbers;)
{
Console.Write("\nEnter number: ");
string entered = Console.ReadLine();
int val;
//checks to see if valid number
if (!Int32.TryParse(entered, out val))
{
Console.Write("Invalid number '{0}'", entered);
array[i++] = val;
}
//checks to see if already entered
else if (i > 0 && array.Take(i).Contains(val))
{
Console.Write("{0} has already been entered", val);
array[i++] = val;
}
//prints inputted integer
else {
array[i++] = val;
Console.WriteLine("{0}", val);
}
}
}
Just loop over the array so far printing each.
Forgive my mobile crafted code, but more or less this:
//prints inputted integer
else {
array[i++] = val;
for(int j=0 ; j<i;j++) {
Console.WriteLine("{0}", array[j]);
}
}
You may use foreach loop
foreach(int num in array)
{
Console.WriteLine("{0}", num);
}
Very Basic approach, try one of the following:
for(var x=0;x<array.length;x++)
or
foreach(var i in array)
But your use case, use HashSet data structure
Mathematically, Set is unique list of things.
try this code, it uses a Dictionary to keep the list in memory and to search to see if the an integer has been added,
using System.Collections.Generic;
static void Main(string[] args)
{
//checks how many numbers will be entered
int manyNumbers;
Console.WriteLine("How many numbers will you enter?");
manyNumbers = Convert.ToInt32(Console.ReadLine());
Dictionary<int, int> array = new Dictionary<int, int>();
//starts asking for numbers
for (int i = 0; i < manyNumbers; )
{
Console.Write("\nEnter number: ");
string entered = Console.ReadLine();
int val;
//checks to see if valid number
if (!Int32.TryParse(entered, out val))
{
Console.Write("Invalid number '{0}'", entered);
}
//checks to see if already entered
else
if (i > 0 && array.ContainsKey(val))
{
Console.Write("{0} has already been entered", val);
//array[i++] = val;
}
else
{
//* add the new integer to list
array.Add(val, 0);
//prints the complete list
List<int> keys = new List<int>(array.Keys);
Console.WriteLine();
for(int j=0; j<keys.Count; j++) Console.WriteLine(keys[j]);
}
}
}