Index variable breaking? Looping in C#, Visual Studio 2015 - c#

today I have an issue which is driving me up a wall. I am a novice programmer, currently learning the basics of C#, after learning Java.
Today, I was working on a practice example when I encountered this problem:
Code Running
This is a screenshot of my code running, and I have left a print statement inside the loop to show me what my index variable is doing. As you can see, it is incrementing more than once per each execution of the loop. I have also gotten the same results when using a while loop, and in other projects.
Here is the code:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("How many values are you entering");
int value = Convert.ToInt32(Console.Read());
Console.WriteLine("Please enter the values of the currencies you are converting.");
decimal[] money = new decimal[value];
for (int i = 0; i < money.Length; i++)
{
money[i] = Convert.ToDecimal(Console.Read());
Console.WriteLine("i is: "+i);
}
}
}
I cannot really proceed with this assignment until I can figure out what is causing this issue. Thanks!

try ReadLine() instead of Read() like
Console.WriteLine("How many values are you entering");
string input = Console.ReadLine();
int value = Convert.ToInt32(input);
Console.WriteLine(value +" Please enter the values of the currencies you are converting.");
decimal[] money = new decimal[value];
for (int i = 0; i < money.Length; i++)
{
money[i] = Convert.ToDecimal(Console.ReadLine());
Console.WriteLine("i is: " + i);
}

Hi Welcome to the wonderful world of C#
Your problem here is Console.Read()
Console.Read() will give you an int of the character 4 which is your first typed character. And that character will be 52.
So it will loop 52 times.
Instead of Console.Read() use Console.ReadLine()

Related

Trying to fix counting in c#

So this is a very simple code that i can for the love of me get right because of some small mistake but the point here is the first int the user gives is the amount of numbers you will give after it so i have made this but for some reason the program wants 1 more int than it should. Lets say i enter 3 at first. That should mean that it would take 3 ints after that and then print them and end the program but fore some reason if i enter 3 after that it wants 4. if i enter 4 after that it wants 5 and you get the point. I have tried changing the whole code but i think the problem is that i am just making it to long and to complicated. here is the code
using System;
namespace Homework_PrPr
{
class Program
{
static void Main(string[] args)
{
int ammount = int.Parse(Console.ReadLine());
int Enters = int.Parse(Console.ReadLine());
int[] numbers = new int[ammount];
for(int i = 0; i < ammount; i++)
{
numbers[i] = Enters;
Enters = int.Parse(Console.ReadLine());
}
int ammountEntered = 0;
while(ammountEntered < ammount)
{
Console.WriteLine(numbers[ammountEntered]);
ammountEntered++;
}
}
}
}
int ammount = int.Parse(Console.ReadLine());
int Enters = int.Parse(Console.ReadLine());
Take a moment to think about this. If the user enters amount = 1, what would Happen? You would first ask a number, then enter the loop one time, where it asks for another number. Why is it asking for another number in this case? Why not just skip the Enter variable and assign numbers inside the loop?
for(int i = 0; i < ammount; i++)
{
numbers[i] = int.Parse(Console.ReadLine());
}
I would highly recommend reading eric lipperts article on How to debug small programs, since problems like this should be very easy to diagnose when stepping thru a program. You might also consider reading the coding convensions guide, local variables should for example use "camelCasing".
You might also consider using a foreach loop when printing variables:
foreach(var number in numbers){
Console.WriteLine(number);
}
I think i understand your code!
This is how i would do it, and do read my explanation down below aswell!
using System;
namespace Homework_PrPr
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("How many numbers do you want to add to your array?");
int amount = int.Parse(Console.ReadLine());
int[] numbers = new int[amount];
for (int i = 0; i < amount; i++)
{
Console.WriteLine($"Numer {i+1}/{amount}"); // Just tells the user what I of number their adding. aka unessecary
int Enters = int.Parse(Console.ReadLine());
numbers[i] = Enters;
}
Console.WriteLine("\n");
int ammountEntered = 0;
while (ammountEntered < amount)
{
Console.Write($"Number {ammountEntered + 1}/{amount} : ");
Console.WriteLine(numbers[ammountEntered]);
ammountEntered++;
}
}
}
}
The first problem was that you asked for a unnesecary ReadLine in the beggining, so that i removed! Then inside you for-loop i switched the position of the adding, aswell as the one asking for a new number. I also added a few counters so that you can see a bit more in detail what the code does!

c# Roll Dice simulation to return how many times every side landed

My first post on here! I started learning how to program a couple of days ago and have picked up a rolling dice project. I think I have done the main part of it but my problem comes from:
Printing how many times each side came up (maybe store them in an array)?
Bonus: Print out the percentage of times each side appeared (rounded up to 2 decimals)
Keep in mind the times and sides are user input so could be e.g. 50 times x 35 sides.
using System;
using System.Collections.Generic;
using System.Security.Cryptography.X509Certificates;
namespace Dice_roll
{
class Program
{
static void Main(string[] args)
{
static int getRandomNumber(int min, int max)
{
Random randomRoll = new Random();
lock (randomRoll)
{
return randomRoll.Next(min, max);
}
}
int sides, rollTimes, i;
i = 0;
bool boolCheckSides = false;
bool boolCheckRolls = false;
Console.WriteLine("Welcome to a little dice rolling program.\n Select how many sides you want the dice to have: \n");
do
{
boolCheckSides = Int32.TryParse(Console.ReadLine(), out sides);
if (boolCheckSides == false)
{
Console.WriteLine("Invalid number.. \n");
}
} while (boolCheckSides == false);
Console.WriteLine("Now select how many times you want it to roll: \n");
do
{
boolCheckRolls = Int32.TryParse(Console.ReadLine(), out rollTimes);
if (boolCheckRolls == false)
{
Console.WriteLine("Invalid number.. \n");
}
} while (boolCheckRolls == false);
do
{
Console.WriteLine("Rolling... " + getRandomNumber(1, sides));
i = i + 1;
System.Threading.Thread.Sleep(500);
} while (i < rollTimes);
int[] arr = new int[rollTimes];
}
}
}
I'm sorry if my code is messy or something, I'm still very beginner.
Well, I assume that your code is not complete yet, so I will just share some opinions of mine.
1- You are adding a method getRandomNumber inside your main function. This method won't compile and should be moved outside the scope of main function. The scope of main function is any code between the curly brackets "{}" shown in the code below
static void main(string[] args){}
just a small side note, try to use Uppercase letters for naming methods in C#, except the main function as that's a naming convention ;-)
2- You did a great job in declaring the variables you need (boolCheckSides, boolCheckRolls, i) before you start assigning them values. However, you also need to declare the Array before using it not after, so your code should look something like this
//Declare the Array
int[] arr = new int[rollTimes];
do
{
int temp = getRandomNumber(1, sides);
Console.WriteLine("Rolling... " + temp);
//Save the value acquired from this roll in the array
arr[i] = temp;
i = i + 1;
System.Threading.Thread.Sleep(500);
} while (i < rollTimes);
Then you can easily play around with the array and find the frequency of any number. I would suggest you refer to this post Count the frequency of element of an array in C# if you want to find the short answer, and refer to this post Frequency of Numbers in a 1D Array for the long answer. Just please note that the second post is using C++ language, but it is still showing the same logic though.
3- Just a small advise, please try to avoid "do...while" loops as much as possible. It needs a lot of attention when you write them as they can easily get you into infinite loop.
I suggest you to use a Dictionary, with the side (1 to X) as Key and number of time its appears .
class Program
{
Dictionary<int, int> RollDice = new Dictionary<int, int>();
static void Main(string[] args)
{
:
Console.WriteLine("Welcome to a little dice rolling program.\n Select how many sides you want the dice to have: \n");
do
{
boolCheckSides = Int32.TryParse(Console.ReadLine(), out sides);
if (boolCheckSides == false)
{
Console.WriteLine("Invalid number.. \n");
}
} while (boolCheckSides == false);
//Initialize the dictionary with key and value
for(int i = 1; i<=sides;i++)
RollDice.Add(i, 0);
:
i = 0;
do
{
var value = getRandomNumber(1, sides + 1)
Console.WriteLine("Rolling... " + value);
RollDice[i]++;
i = i + 1;
System.Threading.Thread.Sleep(500);
} while (i < rollTimes);
and you could display your stats by looping over the dictionary:
foreach (var pair in RollDice)
{
Console.WriteLine($"DiceSide:{pair.Key} , appears: {pair.Value}, probability: {(float)pair.Value/(float)rollTimes:0.00}");
}

A program to calculate the mean and shows the inputs and workings out

I am relatively new to coding and have been set a homework piece for my assignment and I am really struggling with this part. The idea is that i ask for 15 user inputs (using an array) and spit back out the workings out for example 2+6+7+8 etc and then show the answer and average it for example answser from adding/15= the average.
private static void test()
{
int[] array1 = new int[15];
int bAdding;
int bnumberAverage = bAdding / 15;
Console.WriteLine("Please provide 15 numbers and I will tell you the average of them");
for (int i = 0; i < array1.Length; i++)
{
while (int.TryParse(Console.ReadLine(), out array1[i]) == false)
{
Console.WriteLine("Please give me a number not text");
}
}
Console.WriteLine("The average is: {0}", array1.Average());
}
So far it just returns the answer but not the workings. Could someone please help?
Write this at the end:
Console.WriteLine($"{string.Join("+", array1)}={array1.Average()}");
In order to display the results you need to join your array into a string.
var additionSteps = string.Join("+", array1);
Then you can print the result to the console:
Console.WriteLine($"The average is ({additionSteps}) / 15 = {array1.Average()}");

How do I loop a function in c#?

I have been given this question, in my computer science class, and I cannot figure out how to answer it.
Question:
•Create a procedure called tossCoins with one integer parameter - numTosses
•Inside your tossCoins procedure, call your tossCoin function from challenge #5
numTosses times. So for example if we enter tossCoins(50), the tossCoin function will be called 50 times.
•Your tossCoins procedures should then print out the number of times that the coin landed on heads and the number of times the coin landed on tails
•Extend your main program, so that the user can choose how many times to toss the coin
I have already created the tossCoin function, but cannot figure out how to run it the amount of times the user asks, or how to create a tally of heads and tails.
This is the code I have so far:
static void Main(string[] args)
{
Random rnd = new Random();
Console.WriteLine(tossCoin(rnd));
Console.Write("Please enter a number: ");
int numTosses = Convert.ToInt16(Console.ReadLine());
Console.ReadLine();
}
static string tossCoin(Random rnd)
{
int num = rnd.Next(1, 3);
string heads = "Heads";
string tails = "Tails";
if(num == 1)
{
return heads;
}
else
{
return tails;
}
}
static void tossCoins(int numTosses)
{
int headsTally = 0;
int tailsTally = 0;
for(int i = 0; i < numTosses; i++)
{
string outcome = tossCoin(rnd);
numTosses--;
if(outcome == heads)
{
headsTally++;
}
else
{
tailsTally++;
}
}
}
}
If anyone can help, it would be great, as I am trying to learn the different rules of using functions, and procedures. Thanks, Leighton.
A couple things, first it looks like you've almost got it. You just need to call your tossCoins() function in your main method. Second, you don't need to decrement numTosses in your for loop, ie. remove the line numTosses--;
EDIT: as Tommy said, the statement outcome == heads wont compile since heads isn't defined. Either replace heads with "Heads" or define it earlier in the function. And yea you might want to return/print the result.

"System.FormatException" when getting user input from console - visual c#

I am trying to make a command line program that will ask if fast and long you want it to beep. I keep getting System.FormatException on the code below. I get the problem right after Console.WriteLine("how many times should i beep?");. I've found a fix by putting a console.read();//pause right after this line.
My question is what am I doing wrong? or am I suppose to have the pause after that line?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("how fast would you like the sounds to play?");
Console.WriteLine("70 = fast and 300 = slow can pick any number inbetween");
string choice = Console.ReadLine();
int speed = Convert.ToInt32(choice);
Console.Write(speed);
Console.Read();//pause
Console.WriteLine("how many times should i beep?");
string choice2 = Console.ReadLine();
int j = Convert.ToInt32(choice2);
Console.Write(j);
Console.Read();//pause
for (int i = 0 ; i < j; i++)
{
Console.Beep(1000, speed);
}
}
}
My psychic debugging skills tell me that it's this line throwing the exception:
int j = Convert.ToInt32(choice2);
Putting the Console.Read() in like you mentioned before that causes that line not to execute immediately and delaying the throwing of the exception.
If you input something that isn't an integer on this line:
string choice2 = Console.ReadLine();
You will get a FormatException on the following Convert.ToInt32 call.
See the documentation for Convert.ToInt32 where it tells you a FormatException is thrown when the value you pass does not consist of an optional sign followed by a sequence of digits (0 through 9).
To solve your issue, use Int32.TryParse (or just make sure you enter a valid integer). That will return a boolean indicating the success or failure of the parsing rather than throwing an exception.
Also, welcome to StackOverflow! Be sure to upvote answers you find helpful and accept the one that best resolves your question.
why are those extra Console.Read() in there? They are breaking your program, because the user will press return too many times
Console.WriteLine("how fast would you like the sounds to play?");
Console.WriteLine("70 = fast and 300 = slow can pick any number inbetween");
string choice = Console.ReadLine();
int speed = Convert.ToInt32(choice);
Console.WriteLine(speed);
Console.WriteLine("how many times should i beep?");
string choice2 = Console.ReadLine();
int j = Convert.ToInt32(choice2);
Console.Write(j);
for (int i = 0; i < j; i++)
{
Console.Beep(1000, speed);
}
Actually, all you need to do is remove those Read() pauses you threw in. I'd probably also change the Write() calls to WriteLine() calls.
You can also change the Read() calls to ReadLine() calls, if you insist on "pausing" there.
Try this:
Console.Read();
string choice2 = Console.ReadLine();

Categories