I'm pretty new to C# and want the users to be able to write in 5 numbers between 1 to 25. The issue I'm having is that I don't want the user to type a number over 25 or a number below 1.
Also this is a task for my studies and my teacher want us to use arrays so I'm not allowed to use List.
int[] usernum = new int[4];
for (int i = 0; i < usernum.Length; i++)
{
usernum[i] = Convert.ToInt32(Console.ReadLine());
}
Ok, to start off, some annotations to your code:
int[] usernum = new int[4]; // should be: new int[5];
for (int i = 0; i < usernum.Length; i++)
{
usernum[i] = Convert.ToInt32(Console.ReadLine()); // use int.TryParse instead
}
Now, I don't want to just give you the code, since this should obviously be a learning experience.
What you need to do, though is integrate a "validation" cycle. That means:
Read in string from user
Try to parse string to number
If that fails: back to 1.
Check if number < 1 or > 25
If so: back to 1.
If you are here, you passed both checks and can
set usernum[i] = number
Next "i"
Obviously, there are some slight variations in how you twist and turn your checks and arrange loops which are equally valid.
For example: You can decide if you want to check if number is inside bounds or if you want to check if the number is outside bounds and jump or not jump accordingly ...
Why int.TryParse instead of Convert.ToInt32?
There are some rule of thumbs that can spare you from severe headaches:
"Never trust user input"
"Do not use exceptions for control flow"
Using Convert here, breaks both.
For one, Convert.ToInt32 throws if the string does not represent an integer value (chars other than +-0..9, value > int.Max or < int.Min). So in using it, you trust the user to type in a valid integer. Not a good idea.
Then, it throwing means: the case, that a user (maybe just made a typo) did not provide valid input is controlling your flow to error handling. But this case is not at all "exceptional". In fact, you should expect it. int.TryParse makes this possible, in that it returns you a flag (boolean) that informs you about success or failure of the conversion attempt (instead of throwing).
Though I would recommend you to learn if else loop first https://www.w3schools.com/cs/cs_conditions.asp
here is the code if needed
int[] usernum = new int[4];
for (int i = 0; i < usernum.Length; i++)
{
var result = Console.ReadLine();
int currentResult;
if (!int.TryParse(result, out currentResult))
{
Console.WriteLine("Invalid input - must be a valid integer value");
i--;
continue;
}
if(currentResult < 1 || currentResult > 25)
{
Console.WriteLine("Invalid input - must be between 1 & 25");
i--;
continue;
}
usernum[i] = currentResult;
}
for-loop might not be the ideal solution for this use-case where you need to conditionally increment the index.
This should do the trick:
int[] userNumbers = new int[5];
int i = 0;
while (i < userNumbers.Length)
{
string rawInput = Console.ReadLine();
bool isNumberValid = int.TryParse(rawInput, out int inputNumber); // as suggested by #Fildor
if(isNumberValid && inputNumber >= 1 && inputNumber <= 25) // increment counter only if 1 <= input <= 25
{
userNumbers[i] = inputNumber;
i++;
}
}
Related
There was a test in school where we had to write a C# console program that reads positive integers below 100 from user input and then writes out some details like the biggest number. I used a list to store the numbers. I tested it with some random numbers I typed in but the program only adds the numbers to list starting with the second smallest one.
int count = 0;
List<int> bekertek = new List<int>();
int bekert = Convert.ToInt32(Console.ReadLine());
double atlag;
while (bekert > 0 && bekert < 100)
{
bekert = Convert.ToInt32(Console.ReadLine());
count++;
bekertek.Add(bekert);
}
/* This section is only for checking the list's elements
foreach (var i in bekertek)
{
Console.Write(i + " ");
}*/
Console.WriteLine("A bevitt adatok száma: {0}", count);
bekertek.Sort();
bekertek.Remove(bekertek.Last());
atlag = bekertek.Average();
Console.WriteLine("A legnagyobb érték: {0}", bekertek.Last());
Console.WriteLine("A legkisebb érték: {0}", bekertek.First());
Console.WriteLine("Az adatok átlaga: {0}", atlag);
What did I do wrong?
For input in console, I think the do...while loop is the ideal construct. Menus or requesting a number - it covers all of those.
As for what went wrong: Actually it adds all numbers to the collection (that debug code should confirm it). You just remove the smalest number from the collection between Sorting and Display:
bekertek.Sort();
bekertek.Remove(bekertek.Last()); //Should not have done this.
atlag = bekertek.Average();
There is a saying: "The 2 most common issues in Progamming is naming variables, chache invalidation and off-by-one errors." But this specific to make is somewhat unique :)
Edit: As Biesi Grr pointed out, you also ignore the first input:
int bekert = Convert.ToInt32(Console.ReadLine()); //this is never processed
double atlag;
while (bekert > 0 && bekert < 100)
{
bekert = Convert.ToInt32(Console.ReadLine());
count++;
bekertek.Add(bekert);
}
Maybe you wanted to use a ReadKey() here? There is also no need for a counter - that is actually the job of List.Lenght. In any case, a do..while would make that line unessesary any way.
let us make a fixed, do...while version
bool repeat= true;
do{
int bekert = Convert.ToInt32(Console.ReadLine());
if(bekert > 0 && bekert < 100)
bekertek.Add(bekert);
else
repeat = false;
}while(repeat )
I'm trying to understand why I can't print only the members of a subsequence of an array, that is equal to an integer from the input. The array is also read from the console. When i run the program only the first of these members does come up, but with him also a seemingly random number of zeros, while the rest of the subsequence is omitted. If there's a better way than to use a second array, I'll be grateful if you share it. Okay, to specify- I want to know how to print all the members of the aforementioned subsequence, can you please give me a useful advice or sample? Here's the input, output and code:
4 4 56 57 58
8
4 0 0 0 0
instead of 4 4
int v = int.Parse(Console.ReadLine());
int[] valueHolder = new int[arr1.Length];
int currentSum = 0;
for (int endIndex = 0; endIndex <= arr1.Length -1; endIndex++)
{
currentSum = 0;
for (int currentSumIndex = endIndex; currentSumIndex >= 0; currentSumIndex--)
{
currentSum += arr1[currentSumIndex];
if (currentSum == v)
{
valueHolder[currentSumIndex] = arr1[currentSumIndex];
}
if (currentSum == v)
{
for (int i = 0; i <= valueHolder.Length - 1; i++)
{
Console.Write(valueHolder[i] + " ");
}
}
}
I think you would be best served by putting a break point on the line of the first for loop then stepping through your code. If you take a pad of paper and write each of the variables states as you go through it then it will be pretty obvious what's going on.
However, just to help you out.
In the first pass of the outer loop (endIndex = 0), the inner loop does NOT execute. currentSumIndex = endIndex which equals zero, which does not pass the currentSumIndex >= 0 test. Therefore the first 4 is skipped.
In the second pass, the number 4 is emitted because currentSum equals 4. However, the values of 0 are also emitted because you are walking the entire valueHolder array and spitting all of the empty values out.
From the third pass forward, currentSum will never equal the number you typed in:
The first pass of the inner loop sets currentSum to 56, which does not equal v. The second pass of the inner loops sets it to 56+4 ( currentSum += arr1[currentSumIndex] ) which is 60. Therefore, nothing will ever be emitted again as currentSum will always be the sum of all numbers from the current array position going backward to the beginning array position and therefore will always be greater than v
You don't need a second array. You just need to pay attention to what your code is doing. Side note: I have absolutely no idea why you have that inner loop or even what the 8 is supposed to represent in your example entry above.
If I was writing this, I'd change it to (assuming you can't use LINQ):
int v = int.Parse(Console.ReadLine());
for (int i= 0; i <= arr1.Length -1; i++)
{
if (arr1[i] == v) {
Console.Write(arr1[i].ToString() + " ");
}
}
Console.WriteLine();
This question asks to write a program that accepts input for five 'stores'. The input should ideally be a range from 100 to 2000. Each input should be divided by 100, and have that amount displayed in asterisks (i.e. 500 is *, etc.). I believe I have the first part, but I've got no idea how to go about doing the rest. I cannot use arrays, as I have not learned them yet, and I want to be learn this myself instead of just copy-pasting from another student. So far, I only have
int loop;
loop = 1;
while (loop <= 5)
{
string input1;
int iinput1, asteriskcount1;
Console.WriteLine("Input number of sales please!");
input1 = Console.ReadLine();
//store value?
loop = loop + 1;
input1 = Convert.ToInt32(input1);
asteriskcount1 = iinput1 / 10;
}
Not sure if I understand what you're trying to do. But maybe this will help. This is untested, but it should do what I THINK you are asking, but I am unsure what you wanted done with the asterisks. Please explain more if this isn't what you were getting at.
string Stored = "";
for (int i=0; i < 5; i++;)
{
string input1;
int iinput1, asteriskcount1;
Console.WriteLine("Input number of sales please!");
input1 = Console.ReadLine();
//Adds to existing Stored value
Stored += input1 + " is ";
//Adds asterisk
iinput1 = Convert.ToInt32(input1);
asteriskcount1 = iinput1 / 100;
for(int j = 0; j < asteriskcount1; j++)
{
Stored += "*";
}
//Adds Comma
if(i != 4)
Stored += ",";
}
Console.WriteLine(Stored); //Print Result
Don't want to write it out for you but here's some thoughts ...
first, you can do a for loop for the 5 stores:
for (int loop = 0; loop < 5; loop++)
You'll probably want asterickCount (not asterickCount1) since you're in a loop. You'll also want to divide by 100 since you're range is up to 2000 and you have 80 chars on a console. That means it will print up to 20 astericks.
You'll want a PrintAstericks(int count); function that you call right after calculating the asterickCount that you call. That function simply loos and calls Console.Write (not WriteLine) to write an asterick n times (new string has overload to take char and count).
But, that pattern will print the astericks after you take each input. If you want the pattern to be (1) accept the counts for the five stores and then (2) print the asterick rows for all five, you'll need an array with 5 slots to store the inputs then loop through the array and print the asterick rows.
Finally, you'll want to put some validation on the inputs. Look at Int32.TryParse:
http://msdn.microsoft.com/en-us/library/bb397679.aspx
Super easy
int asteriskCount = int.Parse(input1)/ 100;
string output = new string('*', asteriskCount );
I'm trying to create a program where the size of array index and its elements are from user input.
And then the program will prompt the user to search for a specific element and will display where it is.
I've already come up with a code:
using System;
namespace ConsoleApplication1
{
class Program
{
public static void Main(String [] args)
{
int a;
Console.WriteLine("Enter size of index:");
a= int.Parse(Console.ReadLine());
int [] index = new int [a];
for (int i=0; i<index.Length;i++)
{
Console.WriteLine("Enter number:");
index[i]=int.Parse(Console.ReadLine());
}
}
}
}
The problem with this is that I can't display the numbers entered and I don't have any idea how to search for an array element.
I'm thinking of using if statement.
Another thing, after entering the elements the program should display the numbers like Number 0 : 1
Is this correct: Console.WriteLine("Number"+index[a]+":"+index[i]);?
And where should I put the statement? after the for loop or within it?
You're on the right track. Look carefully at how you stuffed values into the array, and you might find a clue about "how to search for an array element" with specific value. This is a core introductory algorithm, so no shortcuts! You need to find the answer on your own :-).
What is the last line Console.WriteLine(index[i]);? It seems like you are using the loop variable outside the loop.
To display entered numbers (ie. if I understand well, the numbers in the array), you have just to walk through the array like this:
for (int i = 0; i < index.length; i++)
{
Console.WriteLine(index[i]);
}
Since you want display numbers only after every number is entered, you may put this code only after finishing the loop where the user is entering the numbers:
// The user is entering the numbers (code copied from your question).
for (int i = 0; i < index.Length; i++)
{
Console.WriteLine("Enter number: ");
index[i] = int.Parse(Console.ReadLine());
}
// Now display the numbers entered.
for (int i = 0; i < index.length; i++)
{
Console.WriteLine(index[i]);
}
// Finally, search for the element and display where it is.
int elementToSearchFor;
if (int.TryParse(Console.ReadLine(), out elementToSearchFor))
{
// TODO: homework to do.
}
To search for a number, you can either walk through the array again and compare each element until finding a good one, or use Linq TakeWhile() method. (I suppose that your intent is not to use Linq, so I don't provide any further detail in this direction.)
You could use Array.IndexOf,
int a;
Console.WriteLine("Enter size of Array:-");
a = int.Parse(Console.ReadLine());
int[] array = new int[a];
Console.WriteLine("Enter the Elements of the Array:-");
for (int i = 0; i < array.Length; i++)
{
array[i] = int.Parse(Console.ReadLine());
}
Console.WriteLine("\nThe Elemets of the Array are:-");
for (int j = 0; j < array.Length; j++)
{
Console.WriteLine(array[j]);
}
Just try to break down what you've done and what you still need to do
Create a program where:
1) size of its array elements comes from user input (check)
2) array elements come from user input (check)
3) Prompt the user to search for a specific element (TODO)
4) Display where it is (TODO)
From the code you've written so far I would think you have most of what you need to do #3 & #4
An if statement may come into play when finding the location of the element the user specifies.
What would be the best way to fill an array from user input?
Would a solution be showing a prompt message and then get the values from from the user?
string []answer = new string[10];
for(int i = 0;i<answer.length;i++)
{
answer[i]= Console.ReadLine();
}
Could you clarify the question a bit? Are you trying to get a fixed number of answers from the user? What data type do you expect -- text, integers, floating-point decimal numbers? That makes a big difference.
If you wanted, for instance, an array of integers, you could ask the user to enter them separated by spaces or commas, then use
string foo = Console.ReadLine();
string[] tokens = foo.Split(",");
List<int> nums = new List<int>();
int oneNum;
foreach(string s in tokens)
{
if(Int32.TryParse(s, out oneNum))
nums.Add(oneNum);
}
Of course, you don't necessarily have to go the extra step of converting to ints, but I thought it might help to show how you would.
It made a lot more sense to add this as an answer to arin's code than to keep doing it in comments...
1) Consider using decimal instead of double. It's more likely to give the answer the user expects. See http://pobox.com/~skeet/csharp/floatingpoint.html and http://pobox.com/~skeet/csharp/decimal.html for reasons why. Basically decimal works a lot closer to how humans think about numbers than double does. Double works more like how computers "naturally" think about numbers, which is why it's faster - but that's not relevant here.
2) For user input, it's usually worth using a method which doesn't throw an exception on bad input - e.g. decimal.TryParse and int.TryParse. These return a Boolean value to say whether or not the parse succeeded, and use an out parameter to give the result. If you haven't started learning about out parameters yet, it might be worth ignoring this point for the moment.
3) It's only a little point, but I think it's wise to have braces round all "for"/"if" (etc) bodies, so I'd change this:
for (int counter = 0; counter < 6; counter++)
Console.WriteLine("{0,5}{1,8}", counter, array[counter]);
to this:
for (int counter = 0; counter < 6; counter++)
{
Console.WriteLine("{0,5}{1,8}", counter, array[counter]);
}
It makes the block clearer, and means you don't accidentally write:
for (int counter = 0; counter < 6; counter++)
Console.WriteLine("{0,5}{1,8}", counter, array[counter]);
Console.WriteLine("----"); // This isn't part of the for loop!
4) Your switch statement doesn't have a default case - so if the user types anything other than "yes" or "no" it will just ignore them and quit. You might want to have something like:
bool keepGoing = true;
while (keepGoing)
{
switch (answer)
{
case "yes":
Console.WriteLine("===============================================");
Console.WriteLine("please enter the array index you wish to get the value of it");
int index = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("===============================================");
Console.WriteLine("The Value of the selected index is:");
Console.WriteLine(array[index]);
keepGoing = false;
break;
case "no":
Console.WriteLine("===============================================");
Console.WriteLine("HAVE A NICE DAY SIR");
keepGoing = false;
break;
default:
Console.WriteLine("Sorry, I didn't understand that. Please enter yes or no");
break;
}
}
5) When you've started learning about LINQ, you might want to come back to this and replace your for loop which sums the input as just:
// Or decimal, of course, if you've made the earlier selected change
double sum = input.Sum();
Again, this is fairly advanced - don't worry about it for now!
C# does not have a message box that will gather input, but you can use the Visual Basic input box instead.
If you add a reference to "Microsoft Visual Basic .NET Runtime" and then insert:
using Microsoft.VisualBasic;
You can do the following:
List<string> responses = new List<string>();
string response = "";
while(!(response = Interaction.InputBox("Please enter your information",
"Window Title",
"Default Text",
xPosition,
yPosition)).equals(""))
{
responses.Add(response);
}
responses.ToArray();
Try:
array[i] = Convert.ToDouble(Console.Readline());
You might also want to use double.TryParse() to make sure that the user didn't enter bogus text and handle that somehow.
I've done it finaly check it and if there is a better way tell me guys
static void Main()
{
double[] array = new double[6];
Console.WriteLine("Please Sir Enter 6 Floating numbers");
for (int i = 0; i < 6; i++)
{
array[i] = Convert.ToDouble(Console.ReadLine());
}
double sum = 0;
foreach (double d in array)
{
sum += d;
}
double average = sum / 6;
Console.WriteLine("===============================================");
Console.WriteLine("The Values you've entered are");
Console.WriteLine("{0}{1,8}", "index", "value");
for (int counter = 0; counter < 6; counter++)
Console.WriteLine("{0,5}{1,8}", counter, array[counter]);
Console.WriteLine("===============================================");
Console.WriteLine("The average is ;");
Console.WriteLine(average);
Console.WriteLine("===============================================");
Console.WriteLine("would you like to search for a certain elemnt ? (enter yes or no)");
string answer = Console.ReadLine();
switch (answer)
{
case "yes":
Console.WriteLine("===============================================");
Console.WriteLine("please enter the array index you wish to get the value of it");
int index = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("===============================================");
Console.WriteLine("The Value of the selected index is:");
Console.WriteLine(array[index]);
break;
case "no":
Console.WriteLine("===============================================");
Console.WriteLine("HAVE A NICE DAY SIR");
break;
}
}
Add the input values to a List and when you are done use List.ToArray() to get an array with the values.
of course....Console.ReadLine always return string....so you have to convert type string to double
array[i]=double.Parse(Console.ReadLine());
readline is for string..
just use read